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

How to make Javascript "toString" implicite method culture aware

在我的 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

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

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)
};