javascript 用两位小数格式化欧洲格式的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30777552/
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
Formatting number in European format with two decimals
提问by RootNode
Trying to format a number to two decimals format in European culture. So that comma is decimal separator and space thousands separator.
试图在欧洲文化中将数字格式化为两位小数格式。所以逗号是十进制分隔符和空格千位分隔符。
In example 213245should be formatted as 213 245,00
在示例中213245应格式化为213 245,00
How can I do that?
我怎样才能做到这一点?
213245.toFixed(2).toLocaleString();
gives 213245.00but it should be 213 245,00
给出213245.00但它应该是213 245,00
however
然而
213245.toLocaleString()
gives 213 245
给出213 245
Fiddling below:
摆弄以下:
var out, input;
input = 213245;
// TEST 1
out = input.toFixed(2);
console.log(out); // 213245.00
out = out.toLocaleString();
console.log(out); // 213245.00
// TEST 2
out = input.toLocaleString();
console.log(out); // 213 245
回答by álvaro González
When you use Number.toFixed()you obtain a string(not a number any more). For that reason, subsequent calls to .toLocaleString()
launch the generic Object.toLocaleString()method that knows nothing about numbers, instead of the Number.toLocaleString()you want.
当您使用Number.toFixed() 时,您将获得一个字符串(不再是数字)。出于这个原因,随后调用.toLocaleString()
启动通用Object.toLocaleString()方法,该方法对数字一无所知,而不是您想要的Number.toLocaleString()。
Having a look at the documentation we can compose something like this (tested in Firefox):
查看文档,我们可以编写如下内容(在 Firefox 中测试):
> Number(213245).toLocaleString("es-ES", {minimumFractionDigits: 2});
"213.245,00"
console.log(Number(213245).toLocaleString("es-ES", {minimumFractionDigits: 2}));
This is a relativelynew addition so make sure to verify browser support. In particular, some runtimes like Node.jsdo not include the full ICU dataset by default.
这是一个相对较新的添加,因此请确保验证浏览器支持。特别是,一些运行时(如Node.js)默认不包含完整的 ICU 数据集。