我有一个脚本,它需要一个大数字并计数。该脚本将数字转换为字符串,以便可以使用逗号对其进行格式化,但我还需要在最后两位数字之前添加一个小数位。我知道这一行处理逗号:
if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
我可以添加类似的代码行来完成添加小数点吗?
我有一个脚本,它需要一个大数字并计数。该脚本将数字转换为字符串,以便可以使用逗号对其进行格式化,但我还需要在最后两位数字之前添加一个小数位。我知道这一行处理逗号:
if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
我可以添加类似的代码行来完成添加小数点吗?
是的,如果你总是想要最后两位之前的小数:
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()
您描述的添加逗号的功能是什么时候。
编辑
经过大量的努力,完整的正确代码:
您确定要小数点在最后两位数字之前吗?这种方式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