How to make Javascript “toString” implicite method

2019-08-08 19:57发布

问题:

in my ASP.NET MVC project, I need to make the JavaScript implicite string representation to be current culture aware, in particular with decimal separators. For example:

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

Here, the console.log(nbr) must display "12.25" in EN-US and "12,25" in fr-FR, without having to explicitly call the toString() method.

Does anyone know a way to accomplish this please?

回答1:

You are probably looking for 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

Just note that it may not be supported in all browsers, or is limited in functionality. You can polyfill it though or handle it manually in those cases:

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

    // or polyfill/handle here...
}

In your case you have to explicitly call toLocalString() for this to work. No way around without some hackish approach (not recommended):

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