在 JavaScript 中使用逗号小数分隔符解析数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18405178/
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
Parsing numbers with a comma decimal separator in JavaScript
提问by Chaos
I used this function to check if a value is a number:
我用这个函数来检查一个值是否是一个数字:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
My program need to work with German values. We use a comma as the decimal separator instead of a dot, so this function doesn't work.
我的程序需要使用德国的价值观。我们使用逗号而不是点作为小数点分隔符,因此此功能不起作用。
I tried to do this:
我试图这样做:
n.replace(",",".")
But it also doesn't seem to work. The exact function I tried to use is:
但它似乎也不起作用。我尝试使用的确切功能是:
function isNumber(n) {
n=n.replace(",",".");
return !isNaN(parseFloat(n)) && isFinite(n);
}
The number looks like this 9.000,28
instead of the usual 9,000.28
if my statement wasn't clear enough.
如果我的陈述不够清楚,数字看起来像这样9.000,28
而不是通常的9,000.28
。
回答by rink.attendant.6
You need to replace (remove) the dots first in the thousands separator, then take care of the decimal:
您需要先替换(删除)千位分隔符中的点,然后处理小数点:
function isNumber(n) {
'use strict';
n = n.replace(/\./g, '').replace(',', '.');
return !isNaN(parseFloat(n)) && isFinite(n);
}
回答by Anthony
var number = parseFloat(obj.value.replace(",",""));
You'll probably also want this to go the other way...
你可能也希望这件事反过来......
obj.value = number.toLocaleString('en-US', {minimumFractionDigits: 2});
回答by Jonathan Batista
I believe the best way of doing this is simply using the toLocaleString method. For instance, I live in Brazil, here we have comma as decimal separator. Then I can do:
我相信最好的方法就是使用 toLocaleString 方法。例如,我住在巴西,这里我们用逗号作为小数点分隔符。然后我可以这样做:
var number = 10.01;
console.log(number)
// log: 10.01
console.log(number.toLocaleString("pt-BR"));
// log: 10,01