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

千位符 #57

Open
bibi7 opened this issue Dec 19, 2019 · 0 comments
Open

千位符 #57

bibi7 opened this issue Dec 19, 2019 · 0 comments

Comments

@bibi7
Copy link
Owner

bibi7 commented Dec 19, 2019

笨比解法:

function thoudrend(num) {
  num = num.toString()
  let count = 0;
  let result = [];
  for (let i = num.length - 1; i >= 0; i--) {
    const item = num[i]
    if (count % 3 === 0 && count !== 0) {
      result.push(',')
    }
    result.push(item)
    count++
  }
  return result.reverse().join('')
}

thoudrend(12345678910)  //"12,345,678,910"

toLocaleString

根据 MDN 解释, number.toLocaleString() 方法返回这个数字 number在特定语言环境下的表示字符串。

const num = 1234567890
console.log(number.toLocaleString()) //"12,345,678,910"

语法

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

locales

locales一般是语言区域判定,详见

options

options对象的属性就有很多了,下面列举一个常用的属性。

  1. style : 默认为 decimal ,表示十进制格式, currency表示货币格式, percent表示百分比格式。

  2. currency :如果style设置为currency,则该属性设置货币符号( USD 表示美元, EUR 表示欧元, or CNY是人民币等等,更多符号参考链接:https://www.currency-iso.org/en/home/tables/table-a1.html

  3. useGrouping : 是否使用千分符,默认为true

  4. minimumIntegerDigits :设置整数最小位数(当整数位数不足时,在前面加0)

  5. minimumFractionDigits :设置小数数最小位数。

这个api还是挺好玩的,如下:

var number = 123456.789;

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

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

// 要求货币格式
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

// 设置整数部分为5位,小数部分为2位,不使用千分符格式
Number(123).toLocaleString('zh-CN', {
  style: 'decimal',
  useGrouping: false,
  minimumIntegerDigits: 5,
  minimumFractionDigits: 2
})
// → "00123.00"

// 设置两位小数的百分比显示
Number(3).toLocaleString('zh-CN', {
  style: 'percent',
  minimumFractionDigits: 2
})
// → "300.00%"
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