toLocalString()的妙用
1. 可以直接得到钱的分割效果
let num = 1000000
num.toLocaleString() // '1,000,000'
2.上面方法或许你还要自己再拼接 ¥ 来达到 ¥1,000,000.00
的效果
用以下方法可以直接得到 ¥1,000,000.00
的效果
let num = 1000000
num.toLocaleString('zh',{ style: 'currency', currency: 'cny' }) // '¥1,000,000.00'
3. 如果你想要达到 CNY 1,000,000.00
的效果可以这样
let num = 1000000
num.toLocaleString('zh',{ style: 'currency', currency: 'cny', currencyDisplay: 'code' }) // 'CNY 1,000,000.00'
4. 也可以达到这种效果 '1,000,000.00人民币'
let num = 1000000
num.toLocaleString('zh',{ style: 'currency', currency: 'cny', currencyDisplay: 'name' }) // '1,000,000.00人民币'
5. 可以转换日期
new Date().toLocaleString() // '2022/1/7 下午2:00:05'
6.可以转百分比
let num = 0.52
num.toLocaleString('zh',{ style: 'percent' }) // '52%'
7. 拓展一个获取随机值的小方法
Math.random().toString(36).slice(2) // 'gxiyxzz5wod'