字符串用 JavaScript 固定?
我有一个数字,我需要将其格式化为货币,为此,我必须将我的数字转换为字符串并运行一个函数,这是有效的,但它显示为 X 位小数,是否可以在字符串吗?我尝试过,但没有运气,我不确定如何将字符串转回数字,我只使用了 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;
目前 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 ;
I have a number which I needed to format as currency, to do this im having to turn my number into a string and run a function, This is working but its showing to X decimal places, Is it possible to use 'toFixed' on a string at all? I've tried with no luck and im unsure how to turn the string back into a number, I've used parseInt only it stops at the first character as it doesnt read past my delimeter...
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;
at the moment the amount variable showing as 1,234,567.890123
Thanks for the help all ,
Managed to get it working with this
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 ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定您所说的货币是什么意思 -
这会为千位分隔符添加逗号,并强制输入两位小数,
输入可以是带或不带逗号的数字字符串、减号和小数,或者是数字
Not sure what you mean by currency-
this adds commas for thousands separators and forces two decimal places
input can be a string of digits with or without commas, minus sign and decimal, or a number
我推荐 phpjs 项目中的“number_format”函数:
http://phpjs.org/functions/number_format:481
用法:
就像 PHP 函数一样... http://php.net/manual/en/function.number-format.php
I recommend the "number_format" function from the phpjs project:
http://phpjs.org/functions/number_format:481
Usage:
Just like the PHP function... http://php.net/manual/en/function.number-format.php