问题描述
|
我有一个数字,需要将其格式化为货币,要执行此操作,必须将我的数字转换为字符串并运行一个函数,这是可行的,但它显示为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 ;
解决方法
不知道您所说的货币-
这将为千位分隔符添加逗号并强制使用两位小数
输入可以是带或不带逗号,减号和小数的数字字符串或数字
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
*/
, 我建议使用phpjs项目中的\“ number_format \”函数:
http://phpjs.org/functions/number_format:481
用法:
amount = number_format(EstimatedTotal,2,\'.\',\',\');
就像PHP函数一样... http://php.net/manual/zh/function.number-format.php