大部分前端都不知道的toLocaleString的隐藏用法

202 阅读1分钟

对于toLocaleString()方法相信大家都不陌生,一般我们都是用来根据本地时间将Date对象转换成字符串,将数组转换成字符串。

用法1

const date = new Date();
console.log(date.toLocaleString()); // 2022/1/10 下午1:35:07

用法2

var array = ['张三', '李四', '王五'];
console.log(array.toLocaleString()); // 张三,李四,王五

但,仅此而已吗?

No!toLocaleString可比我们想象的强大多了,废话不多说,上干货。。。

语法

toLocaleString([locales [, options]])

参数

locales 可选,缩写语言代码的字符串或者这些字符串组成的数组。

options 可选,包含一些或所有的下面属性的类

  • decimal用于纯数字格式
  • currency用于货币格式
  • percent用于百分比格式
  • unit用于单位格式

示例

var number = 123456.789;

// 德国使用逗号作为小数分隔符,分位周期为千位
console.log(number.toLocaleString('de-DE'));
// → 123.456,789

// 在大多数阿拉伯语国家使用阿拉伯语数字
console.log(number.toLocaleString('ar-EG'));
// → ١٢٣٤٥٦٫٧٨٩

// 印度使用千位/拉克(十万)/克若尔(千万)分隔
console.log(number.toLocaleString('en-IN'));
// → 1,23,456.789

// nu 扩展字段要求编号系统,e.g. 中文十进制
console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
// → 一二三,四五六.七八九

// 当请求不支持的语言时,例如巴厘语,加入一个备用语言,比如印尼语
console.log(number.toLocaleString(['ban', 'id']));
// → 123.456,789
var number = 123456.789;

// 要求货币格式
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €

// 日元不使用小数位
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457

// 限制三位有效数字
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000
var prices = ['¥7', 500, 8123, 12];
prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });

// "¥7,¥500,¥8,123,¥12"