我有一个以用户本地化格式显示小数的网页,如下所示:
I've got a web page that displays decimals in a user's localized format, like so:
7.757,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.57,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; }
这篇关于JavaScript 是否考虑本地小数分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Electron 渲染器进程中创建子窗口时如何修复How to fix BrowserWindow is not a constructor error when creating child window in Electron renderer process(在 Electron 渲染器进程中创建子窗口
mainWindow.loadURL("https://localhost:3000/") 在 EmainWindow.loadURL(quot;https://localhost:3000/quot;) show white screen on Electron app(mainWindow.loadURL(https://localhost:3000/) 在 Electron 应用程
Electron webContents executeJavaScript:无法在第二个 loaElectron webContents executeJavaScript : Cannot execute script on second on loadURL(Electron webContents executeJavaScript:无法在第二个 loadURL 上
如何在angular-cli的组件内使用电子浏览器窗口?how to use electron browser window inside components in angular-cli?(如何在angular-cli的组件内使用电子浏览器窗口?)
ElectronJS - 在 Windows 之间共享 redux 存储?ElectronJS - sharing redux store between windows?(ElectronJS - 在 Windows 之间共享 redux 存储?)
如何在电子应用程序中访问相机/网络摄像头?How to access camera/webcamera inside electron app?(如何在电子应用程序中访问相机/网络摄像头?)