跳至主要內容

Mr.He小于 1 分钟

更好的方式:

(1234).toLocaleString();
// 目标:1234 -> "1.234"

// 修正方案:
(1234)
 .toString()
 .split('')
 .reverse()
 .join('')                   // "4321"
 .match(/\d{1,3}/g)          // 使用 1到3 的匹配,防止丢失数字 -> ["432", "1"]
 .join('.')                  // "432.1"
 .split('')                  // 转为数组才能用 reverse
 .reverse()                  // ["1", ".", "2", "3", "4"]
 .join('');                  // "1.234"

function format(n){
  let num = n.toString()
  let decimals = ''
  let int = ''
  if(num.includes('.')) {
    [int, decimals] = num.split('.')
  }
  const end = decimals ? '.'+decimals : ''
  if(int.length < 3){
    return n
  }else{
    let left = int.length % 3
    if(left > 0){
      return int.slice(0, left) + ',' + int.slice(left).match(/\d{3}/g).join(',') + end
    }else{
      return int.slice(left).match(/\d{3}/g).join(',') + end
    }
  }
}
format(12345.88)