不同文化中的 JavaScript parseFloat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12694455/
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
JavaScript parseFloat in Different Cultures
提问by chumphries
I have a question about the default behavior of JavaScript's parseFloat function in different parts of the world.
我有一个关于 JavaScript 的 parseFloat 函数在世界不同地区的默认行为的问题。
In the US, if you call parseFloat on a string "123.34", you'd get a floating point number 123.34.
在美国,如果对字符串“123.34”调用 parseFloat,则会得到浮点数 123.34。
If I'm developing code in say Sweden or Brazil and they use a comma instead of a period as the decimal separator, does the parseFloat function expect "123,34" or "123.34".
如果我在瑞典或巴西开发代码并且他们使用逗号而不是句点作为小数点分隔符,那么 parseFloat 函数是否需要“123,34”或“123.34”。
Please note that I'm not asking how to parse a different culture's number format in the US. I'm asking does parseFloat in Sweden or Brazil behave the same way it does inside the US, or does it expect a number in its local format? Or to better think about this, does a developer in Brazil/Sweden have to convert strings to English format before it can use parseFloat after extracting text from a text box?
请注意,我不是在问如何解析美国不同文化的数字格式。我问的是 parseFloat 在瑞典或巴西的行为是否与在美国境内的行为相同,或者它是否需要本地格式的数字?或者为了更好地考虑这一点,巴西/瑞典的开发人员是否必须将字符串转换为英文格式,然后才能在从文本框中提取文本后使用 parseFloat?
Please let me know if this doesn't make sense.
如果这没有意义,请告诉我。
回答by Alcides Queiroz Aguiar
parseFloat
doesn't use your locale's definition, but the definition of a decimal literal.
parseFloat
不使用您的语言环境的定义,而是使用十进制文字的定义。
It only parses .
not ,
它只解析.
不,
I'm brazilian and I have to replace comma with dot before parsing decimal numbers.
我是巴西人,在解析十进制数之前,我必须用点替换逗号。
回答by Bergi
No, parseFloat
is specifiedto parse DecimalLiterals
, which use the dot as decimal separator. It does not depend on the current environment's locale settings.
不,parseFloat
被指定为 parse DecimalLiterals
,它使用点作为小数点分隔符。它不依赖于当前环境的区域设置。
回答by David Hellsing
It's not just Sweden/Brazil. F.ex in US they often add commas in large numbers, like $5,762,325.25
.
不仅仅是瑞典/巴西。F.ex 在美国,他们经常大量添加逗号,例如$5,762,325.25
.
The parseFloat
function essentially deals with decimals, not locale strings.
该parseFloat
函数主要处理小数,而不是语言环境字符串。
In general, JavaScript can sometimes convert generic strings/numbers/dates to locale-friendly formats, but not the other way around.
一般来说,JavaScript 有时可以将通用字符串/数字/日期转换为语言环境友好的格式,但反过来不行。