开发者

Javascript: Convert a number into a well formatted string

In javascript, I have some numbers.

23, 100000, 5000, 45.543

I want to convert each number into a well-formatted string e.g.

'23.00', '1,000,000.00', '5,000.00' , '45.54'

How do I do that in javascript ?

I can do it easily in java (where there is a textformatter 开发者_如何学编程class for this)

thanks,


function CommaFormatted(amount)
{
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.',2)
    var d = a[1];
    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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜