Javascript 如何格式化数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5731193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format numbers?
提问by Kanak Vaghela
I want to format numbers using JavaScript.
我想使用 JavaScript 格式化数字。
For example:
例如:
10 => 10.00
100 => 100.00
1000 => 1,000.00
10000 => 10,000.00
100000 => 100,000.00
回答by Michael - Where's Clay Shirky
If you want to use built-in code, you can use toLocaleString()with minimumFractionDigits, although browser compatibility for the extended options on toLocaleString()is limited.
如果您想使用内置代码,您可以使用toLocaleString()with minimumFractionDigits,尽管 上扩展选项的浏览器兼容性toLocaleString()是有限的。
var n = 100000;
var value = n.toLocaleString(
undefined, // leave undefined to use the browser's locale,
// or use a string like 'en-US' to override it.
{ minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'
If you're using Node.js, you will need tonpm installthe intlpackage.
回答by Adrian Panasiuk
Short solution:
简短的解决方案:
var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,',')
// "1,234,567,890"
回答by Ortiga
Use
用
num = num.toFixed(2);
Where 2 is the number of decimal places
其中 2 是小数位数
Edit:
编辑:
Here's the function to format number as you want
这是根据需要格式化数字的功能
function formatNumber(number)
{
number = number.toFixed(2) + '';
x = number.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '' + ',' + '');
}
return x1 + x2;
}
Sorce: www.mredkj.com
回答by T.J. Crowder
On browsers that supportthe ECMAScript? 2016 Internationalization API Specification(ECMA-402), you can use an Intl.NumberFormatinstance:
在浏览器支持的ECMAScript的?2016 Internationalization API Specification(ECMA-402),可以使用一个Intl.NumberFormat实例:
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
if (typeof Intl === "undefined" || !Intl.NumberFormat) {
console.log("This browser doesn't support Intl.NumberFormat");
} else {
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
}
回答by Pebbl
Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.
由于 JasperV 发现的错误 - 好点!— 我已经重写了我的旧代码。我想我只将它用于带有两位小数的正值。
Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.
根据您要实现的目标,您可能需要舍入与否,因此这里有两个版本跨越该鸿沟。
First up, with rounding.
首先,四舍五入。
I've introduced the toFixed()method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.
我已经介绍了该toFixed()方法,因为它可以更好地准确地处理到特定小数位的舍入并且得到很好的支持。然而,它确实减慢了速度。
This version still detaches the decimal, but using a different method than before. The w|0part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in kand then subtracts it again from the original number, leaving the decimal by itself.
此版本仍然分离小数,但使用与以前不同的方法。该w|0部分删除小数。有关更多信息,这是一个很好的答案。然后留下剩余的整数,将其存储k,然后从原始数字中再次减去它,留下小数本身。
Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit b. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like -,100.00
此外,如果我们要考虑负数,我们需要 while 循环(跳过三位数)直到我们点击b。这在处理负数时被计算为 1,以避免输入类似-,100.00
The rest of the loop is the same as before.
循环的其余部分与之前相同。
function formatThousandsWithRounding(n, dp){
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
s = ''+k, i = s.length, r = '';
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
In the snippet below you can edit the numbers to test yourself.
在下面的代码段中,您可以编辑数字来测试自己。
function formatThousandsWithRounding(n, dp){
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
s = ''+k, i = s.length, r = '';
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
var dp;
var createInput = function(v){
var inp = jQuery('<input class="input" />').val(v);
var eql = jQuery('<span> = </span>');
var out = jQuery('<div class="output" />').css('display', 'inline-block');
var row = jQuery('<div class="row" />');
row.append(inp).append(eql).append(out);
inp.keyup(function(){
out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));
});
inp.keyup();
jQuery('body').append(row);
return inp;
};
jQuery(function(){
var numbers = [
0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
], inputs = $();
dp = jQuery('#dp');
for ( var i=0; i<numbers.length; i++ ) {
inputs = inputs.add(createInput(numbers[i]));
}
dp.on('input change', function(){
inputs.keyup();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
Now the other version, without rounding.
现在是另一个版本,没有四舍五入。
This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.
这采取了不同的路线并试图避免数学计算(因为这会引入舍入或舍入错误)。如果您不想四舍五入,那么您只是将事物作为字符串处理,即 1000.999 转换为两位小数将永远是 1000.99 而不是 1001.00。
This method avoids using .split()and RegExp()however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about toLocaleString, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).
这种方法避免使用.split()和RegExp()但是,两者相比起来都非常慢。虽然我从 Michael 的关于 的回答中学到了一些新东西toLocaleString,但我也惊讶地发现它——在某种程度上——是所有方法中最慢的(至少在 Firefox 和 Chrome;Mac OSX 中)。
Using lastIndexOf()we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.
使用lastIndexOf()我们找到可能存在的小数点,从那里开始,其他一切都几乎相同。在需要的地方用额外的 0 保存填充。此代码限制为小数点后 5 位。在我的测试中,这是更快的方法。
var formatThousandsNoRounding = function(n, dp){
var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
i = s.lastIndexOf('.'), j = i == -1 ? l : i,
r = e, d = s.substr(j+1, dp);
while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
return s.substr(0, j + 3) + r +
(dp ? '.' + d + ( d.length < dp ?
('00000').substr(0, dp - d.length):e):e);
};
var formatThousandsNoRounding = function(n, dp){
var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
i = s.lastIndexOf('.'), j = i == -1 ? l : i,
r = e, d = s.substr(j+1, dp);
while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
return s.substr(0, j + 3) + r +
(dp ? '.' + d + ( d.length < dp ?
('00000').substr(0, dp - d.length):e):e);
};
var dp;
var createInput = function(v){
var inp = jQuery('<input class="input" />').val(v);
var eql = jQuery('<span> = </span>');
var out = jQuery('<div class="output" />').css('display', 'inline-block');
var row = jQuery('<div class="row" />');
row.append(inp).append(eql).append(out);
inp.keyup(function(){
out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));
});
inp.keyup();
jQuery('body').append(row);
return inp;
};
jQuery(function(){
var numbers = [
0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
], inputs = $();
dp = jQuery('#dp');
for ( var i=0; i<numbers.length; i++ ) {
inputs = inputs.add(createInput(numbers[i]));
}
dp.on('input change', function(){
inputs.keyup();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
I'll update with an in-page snippet demo shortly, but for now here is a fiddle:
我将很快更新一个页内片段演示,但现在这里有一个小提琴:
https://jsfiddle.net/bv2ort0a/2/
https://jsfiddle.net/bv2ort0a/2/
Old Method
旧方法
Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:
为什么要为此使用 RegExp?- 当牙签可以使用时不要使用锤子,即使用字符串操作:
var formatThousands = function(n, dp){
var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r +
(d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};
walk through
走过
formatThousands( 1000000.42 );
First strip off decimal:
首先去掉小数点:
s = '1000000', d = ~ 0.42
Work backwards from the end of the string:
从字符串的末尾向后工作:
',' + '000'
',' + '000' + ',000'
Finalise by adding the leftover prefix and the decimal suffix (with rounding to dpno. decimal points):
通过添加剩余的前缀和小数后缀(四舍五入为dp小数点)来完成:
'1' + ',000,000' + '.42'
fiddlesticks
小提琴手
回答by Cacho Santa
I think with this jQuery-numberformatteryou could solve your problem.
我认为使用这个jQuery-numberformatter可以解决您的问题。
Of course, this is assuming that you don't have problem with using jQuery in your project. Please notice that the functionality is tied to the blurevent.
当然,这是假设您在项目中使用 jQuery 没有问题。请注意,该功能与模糊事件相关联。
$("#salary").blur(function(){
$(this).parseNumber({format:"#,###.00", locale:"us"});
$(this).formatNumber({format:"#,###.00", locale:"us"});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/timdown/jshashtable/hashtable.js"></script>
<script src="https://cdn.jsdelivr.net/gh/hardhub/jquery-numberformatter/src/jquery.numberformatter.js"></script>
<input type="text" id="salary">
回答by John Giotta
Use the Number function toFixedand this function to add the commas.
使用 Number 函数toFixed和此函数添加逗号。
function addCommas(nStr)
{
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '' + ',' + '');
}
return x1 + x2;
}
n = 10000;
r = n.toFixed(2); //10000.00
addCommas(r); // 10,000.00
回答by Ashish Gupta
function numberWithCommas(x) {
x=String(x).toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
}
console.log(numberWithCommas(100000));
console.log(numberWithCommas(10000000));
Output
输出
1,00,000
1,00,00,000
1,00,000
1,00,00,000
回答by oezi
Thisis an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):
这是一篇关于你的问题的文章。添加千位分隔符不是 JavaScript 内置的,因此您必须像这样编写自己的函数(示例取自链接页面):
function addSeperator(nStr){
nStr += '';
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, '' + ',' + '');
}
return x1 + x2;
}
回答by Rahul Desai
If you are looking for a formatting with limit to three significant digits, for example:
如果您正在寻找限制为三位有效数字的格式,例如:
1,23,45,67,890.123
Use:
用:
number.toLocaleString('en-IN');
Working Example:
工作示例:
let number = 1234567890.123;
document.write(number.toLocaleString('en-IN'));
Tested in Chrome v60.0.3112.113
在 Chrome v60.0.3112.113 中测试

