我有一个我需要格式化为货币的数字,为此我必须将我的数字变成一个字符串并运行一个函数,这是有效但它显示到X小数位,是否可以使用'toFixed '在一根绳子上?我试过没有运气,我不确定如何将字符串转回一个数字,我已经使用了parseInt,它只停在第一个字符,因为它没有读过我的分隔符......
var amount = String(EstimatedTotal);
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;
目前金额变量显示为1,234,567.890123
感谢所有人的帮助,
管理让它使用此
amount = String(EstimatedTotal)
amount += '';
x = amount.split('.');
x1 = x[0];
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
num=x1 ;
答案 0 :(得分:0)
我推荐phpjs项目中的“number_format”函数:
http://phpjs.org/functions/number_format:481
用法:
amount = number_format(EstimatedTotal, 2, '.', ',');
就像PHP函数一样...... http://php.net/manual/en/function.number-format.php
答案 1 :(得分:0)
不确定货币的含义 -
这会为数千个分隔符添加逗号并强制使用两个小数位
输入可以是带或不带逗号的数字字符串,减号和小数,或数字
function addCommas2decimals(n){
n= Number(String(n).replace(/[^-+.\d]+/g, ''));
if(isNaN(n)){
throw new Error('Input must be a number');
}
n= n.toFixed(2);
var rx= /(\d+)(\d{3})/;
return n.replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
var s= '1234567.890123'
addCommas2decimals(s)
/* returned value: (String)
1,234,567.89
*/