javascript 在 Node.js 中使用 .toLocaleString()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23199909/
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
Using .toLocaleString() in Node.js
提问by AlbertEngelB
So I was writing a small helper method to convert numbers into a valid money format ($xx,xxx.xx
) using .toLocaleString()
. Everything works as expected when using it inside Chrome, however it seems completely broken when using inside Node.js.
所以我正在编写一个小的辅助方法,$xx,xxx.xx
使用.toLocaleString()
. 在 Chrome 中使用它时一切都按预期工作,但是在 Node.js 中使用时它似乎完全坏了。
Example:
例子:
var n = 6000
console.log( n.toLocaleString('USD', {
style: 'currency',
currency: "USD",
minimumFractionDigits : 2,
maximumFractionDigits : 2
}) );
If you run this in the browser, it prints $6,000.00
. If you run this snippet inside of Node.js REPL or application, it returns 6000
as a String.
如果你在浏览器中运行它,它会打印$6,000.00
. 如果您在 Node.js REPL 或应用程序中运行此代码段,它会6000
以字符串形式返回。
Guessing this is a bug with Node.js? Is there a work around you could do here?
猜测这是 Node.js 的错误?你可以在这里做一些工作吗?
回答by Aaron Dufour
Based on this issueit appears that it was decided that shipping node.js with internationalization would make it too large. You can npm install intl
and require that, and it will replace toLocaleString
with a version that works.
基于这个问题,似乎决定运送具有国际化的 node.js 会使它变得太大。您可以npm install intl
并要求这样做,它将替换toLocaleString
为有效的版本。
回答by AlbertEngelB
Just in case someone else stumbles upon this, here's how I formatted a number into a valid US dollar string while in a Node.js environment.
以防万一其他人偶然发现这一点,以下是我在 Node.js 环境中将数字格式化为有效美元字符串的方法。
Number.prototype.toMoney = function() {
var integer = this.toString().split('.')[0];
var decimal = this.getDecimal();
integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if( !decimal || !decimal.length ) {
decimal = "00";
} else if ( decimal.length === 1) {
decimal += '0';
} else if ( decimal.length > 2 ) {
decimal = decimal.substr(0, 2);
}
return '$' + integer + '.' + decimal;
};
Number.prototype.getDecimal = function() {
var n = Math.abs(this);
var dec = n - Math.floor(n);
dec = ( Math.round( dec * 100 ) / 100 ).toString();
if( dec.split('.').length ) {
return dec.split('.')[1];
} else return "";
};
There are a few boo-boo's here, namely extending the native Number
prototype. You will want to avoid this is 90% of the time; this is more specific to my particular implementation.
这里有一些嘘声,即扩展原生Number
原型。在 90% 的情况下,您都希望避免这种情况;这更具体到我的特定实现。
I blatantly stole the regex for formatting the commas from this question.and hacked together the decimal support of my own volition. Mileage may vary.
回答by mts knn
Here's one way to fix this problem:
这是解决此问题的一种方法:
Run
npm install full-icu --save
. According to site.icu-project.org:ICU is a mature, widely used set of –?– libraries providing Unicode and Globalization support for software applications. ICU is widely portable and gives applications the same results on all platforms –?–.
Optionally, run also
npm install cross-env --save
to support Windows users.Update the
scripts
section ofpackage.json
, for example:{ "scripts": { // Omit the "cross-env" part if you didn't install the package in step two "start": "cross-env NODE_ICU_DATA=node_modules/full-icu index.js" } }
运行
npm install full-icu --save
。根据site.icu-project.org:ICU 是一套成熟的、广泛使用的 –?– 库,为软件应用程序提供 Unicode 和全球化支持。ICU 具有广泛的可移植性,并在所有平台上为应用程序提供相同的结果 –?–。
或者,也
npm install cross-env --save
可以运行以支持 Windows 用户。更新 的
scripts
部分package.json
,例如:{ "scripts": { // Omit the "cross-env" part if you didn't install the package in step two "start": "cross-env NODE_ICU_DATA=node_modules/full-icu index.js" } }
This way, when you run npm start
, the full ICU data will be activated, and you should get consistent results between browser and server environments.
这样,当您运行 时npm start
,将激活完整的 ICU 数据,并且您应该在浏览器和服务器环境之间获得一致的结果。
Disclaimer: I haven't tested whether this affects performance. In my case, I did this to fix Jest tests of an app that runs in the browser, so a small performance hit would have been acceptable.
免责声明:我还没有测试这是否会影响性能。在我的例子中,我这样做是为了修复在浏览器中运行的应用程序的 Jest 测试,所以小的性能损失是可以接受的。
Kudos to Rndmax's answer here: Date toLocaleDateString in node
在这里感谢 Rndmax 的回答:节点中的日期 toLocaleDateString
回答by Tony Rossi
So to update this for anyone facing the same issue...
因此,要为面临相同问题的任何人更新此信息...
We had used intlfor our localization solution when server side rendering, but we recently had a requirement to add {timeZoneName: 'short'}
to our .toLocaleString()
options and this field is not supported.
我们在服务器端渲染时将intl用于我们的本地化解决方案,但我们最近需要添加{timeZoneName: 'short'}
到我们的.toLocaleString()
选项中,并且不支持此字段。
Source Code from intl.js:
来自 intl.js 的源代码:
case 'timeZoneName':
fv = ''; // ###TODO
break;
Additionally, there was a breaking change in the latest patch release which forced us to lock down our version to 1.2.4.
此外,最新补丁版本中有一个重大变化,迫使我们将版本锁定到 1.2.4。
Ultimately, we dropped usage of intlin favor of full-icu. Simply adding it to our yarn.lock solved all our Node.js server side date localization issues. Haven't verified currency localization, but so far so good. I recommend giving it a try.
最终,我们放弃了intl 的使用,转而使用full-icu。简单地将它添加到我们的 yarn.lock 解决了我们所有的 Node.js 服务器端日期本地化问题。尚未验证货币本地化,但到目前为止还不错。我建议尝试一下。