blog icon indicating copy to clipboard operation
blog copied to clipboard

Number.prototype.toLocaleString() 方法

Open chenxiaochun opened this issue 7 years ago • 0 comments

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

参考链接

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
  • https://www.zhihu.com/question/20797118
  • html 语言编码表:https://www.w3schools.com/tags/ref_language_codes.asp

chenxiaochun avatar Jul 10 '18 02:07 chenxiaochun