JavaScript是否考虑了本地小数分隔符? [英] Does JavaScript take local decimal separators into account?
问题描述
我有一个网页,以用户的本地化格式显示小数,如下所示:
I've got a web page that displays decimals in a user's localized format, like so:
- 英文:
7.75
- 荷兰语:
7,75
- English:
7.75
- Dutch:
7,75
如果我在我的机器上的JavaScript中添加两个数字变量(其中数字来自上述格式的字符串),我得到以下结果:
If I add two number variables together in JavaScript on my machine (where the numbers are taken from strings in the above formats) I get the following results:
- 英语:
7.75 + 7.75 = 15.5
- 荷兰语:
7,75 + 7,75 = 0
- English:
7.75 + 7.75 = 15.5
- Dutch:
7,75 + 7,75 = 0
如果我要运行此代码在荷兰用户机器上,我应该期望英文格式的添加返回 0
,以及荷兰格式的添加返回 15,5
?
If I was to run this code on a Dutch users machine, should I expect the English-formatted addition to return 0
, and the Dutch-formatted addition to return 15,5
?
简而言之:JavaScript计算是否在其字符串中使用局部小数分隔符来编号转换?
In short: Does the JavaScript calculation use local decimal separators in its string to number conversions?
推荐答案
不,分隔符始终是javascript Number
中的点(。)。所以 7,75
评估为 75
,因为,
调用从左到右的评估(在控制台中尝试: x = 1,x + = 1,alert(x)
,或更多到点 var x =(7,75); alert(x);
)。如果你想转换一个荷兰语(好吧,不仅仅是荷兰语,让我们说 Continental 欧洲)格式化的值,它应该是 String
。你可以写一个 String
原型的扩展名,例如:
No, the separator is always a dot (.) in a javascript Number
. So 7,75
evaluates to 75
, because a ,
invokes left to right evaluation (try it in a console: x=1,x+=1,alert(x)
, or more to the point var x=(7,75); alert(x);
). If you want to convert a Dutch (well, not only Dutch, let's say Continental European) formatted value, it should be a String
. You could write an extension to the String
prototype, something like:
String.prototype.toFloat = function(){
return parseFloat(this.replace(/,(\d+)$/,'.$1'));
};
//usage
'7,75'.toFloat()+'7,75'.toFloat(); //=> 15.5
这篇关于JavaScript是否考虑了本地小数分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!