Javascript toFixed localized?

懵懂的女人 提交于 2020-11-27 04:34:38

问题


Do you know if toFixed is a localized function?

I mean, will this:

var n = 100.67287;
alert(n.toFixed(2));

show "100.67" on english US OS/browsers and "100,67" (with comma) on Italian OS/browsers? (Italian or any other local system that uses comma as decimal separator).

Thanks!


回答1:


No, this will always return a point. The ECMA 262-spec [15.7.4.5] states it should be a point.




回答2:


Late addition: with Number.toLocaleString() now available on everything bar IE 10 & below, this works, albeit rather long-winded:

var n = 100.67287;
console.log(n.toLocaleString(undefined, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}));

Using undefined or 'default' for the language code will use the browser default language to format the number.

See developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for full details.

If you're free to extend the Number prototype, you could defined Number.toLocaleFixed().




回答3:


No sadly, there is no real solution in pure jQuery/JavaScript. You'll need Globalize. The problem is that both toFixed() and toLocaleString() take a number and return a string. So you can never use them together. :( If you call foo.toFixed(2).toLocaleString() you won't get the localization (i.e. '1.234' in en should be '1,234' in fr) because its working on the result of toFixed() which is a string, not a number. :(




回答4:


You can use this:

var n = 100.67287;
alert(parseFloat(n.toFixed(2)).toLocaleString());

On my german system the result is

100,67



回答5:


It is easy to hack this limitation.

    var num = 1000.994;
    var fixedDecimals = 2;
    var intPart = parseInt(num.toFixed(fixedDecimals));
    var decimalSeparator = (0.1).toLocaleString()[1]
    var decimalPart = (num % 1).toFixed(fixedDecimals).slice(2);
    console.log(intPart.toLocaleString() + decimalSeparator + decimalPart);


来源:https://stackoverflow.com/questions/2865719/javascript-tofixed-localized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!