Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Number.prototype.toLocaleString() 方法 #56

Open
chenxiaochun opened this issue Jul 10, 2018 · 0 comments
Open

Number.prototype.toLocaleString() 方法 #56

chenxiaochun opened this issue Jul 10, 2018 · 0 comments

Comments

@chenxiaochun
Copy link
Owner

chenxiaochun commented Jul 10, 2018

toLocaleString()方法会根据传入的语言参数,将数值转换成对应语言的本地格式字符串。先看几个示例:

function eArabic(x){
  return x.toLocaleString('ar-EG');
}

console.log(eArabic(123456.789));
// expected output: "١٢٣٬٤٥٦٫٧٨٩"

console.log(eArabic("123456.789"));
// expected output: "123456.789"

console.log(eArabic(NaN));
// expected output: "ليس رقم"

ar-EG表示阿拉伯语言。所以,第一次调用传入的数值被转换成了阿拉伯语言数字;第二次传入的是一个字符串,不做任何转换;第三次传入的NaN也被进行了转换,如果你不相信它是NaN,可以进行一下测试:

isNaN('يس رقم')
// true

使用语法

numObj.toLocaleString([locales [, options]])

locales参数

此参数是一个可选的 BCP 47 语言标签字符串或者字符串数组。它的取值格式一般为以下种:“arab”,“arabext”,“bali”,“beng”,“deva”,“fullwide”,“gujr”,“guru”,“hanidec”,“khmr”,“knda”,“laoo”,“latn”,“limb”,“mlym”,“mong”,“mymr”,“orya”,“tamldec”,“telu”,“thai”,“tibt“。

options参数

此参数是一个可选的参数对象,它主要有以下几个属性值:

  • localeMatcher:指的是本地的匹配算法,默认值为best fit,还有另一个值是lookup
  • style:可以使用的格式化样式,它的参数值主要有:decimal 用于格式化纯数字;currency用于货币的格式化;percent用于百分比格式化;默认值为decimal
  • currency:用于货币格式化。此参数没有默认值。取值一般是 ISO 4217 中规定的货币代码,例如,"USD"表示美元,"EUR"代表欧元,"CNY"代表人民币。如果上面的style参数值为currency,那么它就必须指定一个值。
  • currencyDisplay
let n = 1234

console.log(n.toLocaleString('en-IN',{
  style: 'currency',
  currency: 'USD',
  currencyDisplay: 'symbol'
}))

参考链接

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant