javascript显示演示

<!DOCTYPE html>
<html>
<body>

<script>
/** 下面两个函数都能对浮点数进行四舍五入,保留小数点后两位 **/
function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}
/**
*   Usage:  CurrencyFormatted(12345.678);
*   result: 12345.68
**/
document.write(CurrencyFormatted(12345.6789)+"<br>");

function format_number(pnumber,decimals){
    if (isNaN(pnumber)) { return 0};
    if (pnumber=='') { return 0};
    var snum = new String(pnumber);
    var sec = snum.split('.');
    var whole = parseFloat(sec[0]);
    var result = '';
    if(sec.length > 1){
        var dec = new String(sec[1]);
        dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
        dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
        var dot = dec.indexOf('.');
        if(dot == -1){
            dec += '.';
            dot = dec.indexOf('.');
        }
        while(dec.length <= dot + decimals) { dec += '0'; }
        result = dec;
    } else{
        var dot;
        var dec = new String(whole);
        dec += '.';
        dot = dec.indexOf('.');  
        while(dec.length <= dot + decimals) { dec += '0'; }
        result = dec;
    }
    return result;
}
/**
*   Usage:  format_number(12345.678, 2);
*   result: 12345.68
**/
document.write(format_number(12345.6789,2)+"<br>");

//alert((12345.6789).toFixed(2));    // 虽然有点bug,但能解决很多问题了。

 

function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    amount = new String(amount);
    var a = amount.split('.',2)
    var d = a[0];
    var i = parseInt(a[0]);
    if(isNaN(i)) { return ''; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3)
    {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if(n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if(d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}
/**
*   Usage:  CommaFormatted(12345678);
*   result: 12,345,678.12345678
**/
 document.write(CommaFormatted(1234567898)+"<br>");

 

 


</script>

 

 


</body>
</html>

你可能感兴趣的:(js)