在字符串中添加小数

时间:2011-08-22 16:32:56

标签: javascript string decimal-point

我有一个需要大量数据的脚本。该脚本将数字转换为字符串,以便可以使用逗号格式化,但我还需要在最后两位数之前添加小数位。我知道这行处理逗号:

if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;

我可以添加类似的代码行来完成添加小数点吗?

2 个答案:

答案 0 :(得分:2)

是的,如果你总是想在最后两个之前得到小数:

function numberIt(str) {
    //number before the decimal point
    num = str.substring(0,str.length-3);
    //number after the decimal point
    dec = str.substring(str.length-2,str.length-1)
    //connect both parts while comma-ing the first half
    output = commaFunc(num) + "." + dec;

    return output;
}

commaFunc()是您描述的添加逗号的功能。

修改

经过艰苦努力,完整正确的代码:

http://jsfiddle.net/nayish/TT8BH/21/

答案 1 :(得分:-1)

你确定要小数位于最后两位数之前吗?那样1234将成为12.34而不是1234.00,我假设您想要第二个,在这种情况下,您应该使用JavaScript的内置方法.toFixed()

注意我没有编写format_number函数,我从下面的网站上把它修改了一下。

http://www.mredkj.com/javascript/nfbasic2.html

http://www.mredkj.com/javascript/nfbasic.html

// example 1
var num = 10;
var output = num.toFixed(2); // output = 10.00

// example 2, if you want commas aswell
function format_number(nStr)
{
    nStr = nStr.toFixed(2);
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

var num = 1234;
var output = format_number(num); // output = 1,234.00