如何使Javascript为"toString"隐式方法文化意识 [英] How to make Javascript "toString" implicite method culture aware

查看:159
本文介绍了如何使Javascript为"toString"隐式方法文化意识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC项目中,我需要使JavaScript 隐式字符串表示形式能够了解当前的文化背景,尤其是十进制分隔符. 例如:

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

在这里,console.log(nbr)必须在EN-US中显示为"12.25",而在fr-FR中显示为"12,25",而不必显式调用toString()方法.

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?

推荐答案

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

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.

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

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...
}

在您的情况下,必须显式调用toLocalString()才能起作用.没有一些骇人听闻的方法(不推荐):

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

这篇关于如何使Javascript为"toString"隐式方法文化意识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆