问题描述
我有一个以用户本地化格式显示小数的网页,如下所示:
i've got a web page that displays decimals in a user's localized format, like so:
- 英文:7.75
- 荷兰语: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
如果我要在荷兰用户机器上运行此代码,我是否应该期望英语格式的添加返回 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 european)格式的值,它应该是一个 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
注意,如果浏览器支持,你可以使用 number.tolocalestring
note, if the browser supports it you can use number.tolocalestring
console.log((3.32).tolocalestring("nl-nl")); console.log((3.32).tolocalestring("en-uk"));
.as-console-wrapper { top: 0; max-height: 100% !important; }