How to make Javascript “toString” implicite method culture aware

拥有回忆 提交于 2019-12-11 10:06:49

问题


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


来源:https://stackoverflow.com/questions/29558071/how-to-make-javascript-tostring-implicite-method-culture-aware

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