javascript - 如何使 Javascript "toString"隐式方法文化感知

标签 javascript internationalization tostring culture

在我的 ASP.NET MVC 项目中,我需要使 JavaScript隐式字符串表示能够了解当前文化,特别是使用小数分隔符。 例如:

var nbr = 12.25;
console.log(nbr);

这里,console.log(nbr) 必须在 EN-US 中显示“12.25”,在 fr-FR 中显示“12,25”,而无需显式调用 toString() 方法。

有谁知道如何实现这一点吗?

最佳答案

您可能正在寻找toLocaleString();:

The toLocaleString() method returns a string with a language sensitive representation of this number.

The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

Source

请注意,并非所有浏览器都支持它,或者功能有限。在这些情况下,您可以填充它或手动处理它:

if (typeof Number.prototype.toLocalString === "undefined") {
    // simply make it available
    Number.prototype.toLocalString = Number.prototype.toString;

    // or polyfill/handle here...
}

在您的情况下,您必须显式调用 toLocalString() 才能正常工作。如果没有一些黑客方法就没有办法(不推荐):

Number.prototype.toString = function() {
    return this.toLocaleString(optionsHere)
};

关于javascript - 如何使 Javascript "toString"隐式方法文化感知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29558071/

相关文章:

java - 如何国际化java中的所有UI标签

c# - 如何更改 double.ToString() 中的小数点符号?

javascript - 使用 Jest 和 React 模拟非默认函数

javascript - Electron:在与 index.js 不同的 javascript 中调用函数

java - 如何通过 ServletOutputStream 以 UTF-8 编码发送字符

ios - 在模拟器的设置中更改区域格式,但应用程序中的语言环境没有改变

c# - ToString() 在这里是好是坏还是多余?

f# - 打印F#区分的联合

javascript - for循环完成后执行函数

javascript - 如何在 Ionic popover 中编写函数?