toLocaleString()
方法在很多对象实例上都有,包括:
Object
Number
Date
Array
BigInt
语法格式
obj.toLocaleString([locales[,options]])
, 其中参数如下
locales
(可选)默认为当地的带有BCP 47语言标记的字符串或字符串数组,关于locales参数的形式与解释,请看Intl页面。
options
一个可配置属性的对象,对于数字 Number.prototype.toLocaleString(),对于日期 Date.prototype.toLocaleString().
案例代码:
/**
* toLocalString 方法使用
*/
const numOne = 123.456
console.log(numOne.toLocaleString('zh-u-nu-hanidec')); // 转中文 // 一二三.四五六
// 在没有指定区域的基本使用时,返回使用默认的语言环境和默认选项格式化的字符串。
const numTwo = 1234.5678
console.log(numTwo.toLocaleString()) // 1,234.568
// 当请求不支持的语言时,例如巴厘语,加入一个备用语言,比如印尼语
console.log(numTwo.toLocaleString(['ban', 'id'])); // → 1.234,568
// --------- 使用 options ------------
const numThree = 123456.789
// 货币格式
console.log(numThree.toLocaleString('zh-Hans-CN', {style: 'currency', currency: 'CNY'})) // ¥123,456.79
console.log(numThree.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })) // 123.456,79 €
console.log(numThree.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' })) // ¥123,457(日元不使用小数)
// 百分号
const numFour = 0.34
console.log(numFour.toLocaleString('zh-Hans-CN', { style: 'percent' }));
// --------------------- Date
const date = new Date(2022, 1, 13, 16, 15, 10);
console.log(date); // 2022-02-13T08:15:10.000Z
console.log(date.toLocaleString()); // 2022/2/13 下午4:15:10
console.log(date.toLocaleString('zh-Hans-CN', { hour12: false })); // 2022/2/13 16:15:10
// 相关的两个方法
// date.toLocaleDateString()
// date.toLocaleTimeString()
// Array.prototype.toLocaleString() 对数组中的每个元素调用一次与之对应的 toLocalString()