spaasteam / spaas-daily-practice

spaas团队的每日一练,欢迎小伙伴们提交踊跃答案!
4 stars 2 forks source link

第 32 题: 格式化 money #34

Open cjfff opened 5 years ago

cjfff commented 5 years ago

接受的数字范围: 0 <= n < 2147483647

const formatMoney = n => {

}

example

       1  ->           "1"
      10  ->          "10"
     100  ->         "100"
    1000  ->       "1,000"
   10000  ->      "10,000"
  100000  ->     "100,000"
 1000000  ->   "1,000,000"
35235235  ->  "35,235,235"
Htongbing commented 5 years ago
function format(num) {
  return String(num).split('').reverse().join('').replace(/(?!\d{3}$)(?!\d*\.)(\d{3})/g, '$&,').split('').reverse().join('')
}

console.log(format(1)) // 1
console.log(format(10)) // 10
console.log(format(100)) // 100
console.log(format(1000)) // 1,000
console.log(format(10000)) // 10,000
console.log(format(100000)) // 100,000
console.log(format(1000000)) // 1,000,000
console.log(format(35235235)) // 35,235,235

console.log(format(35235235.123123)) // 35,235,235.123123
cjfff commented 5 years ago
const formatMoney = n => n.toLocaleString("en-US");
// const formatMoney = n => new Intl.NumberFormat().format(n);

// 两种方法都可以,但是有缺点 -> 精度不够

console.log(formatMoney(1)); // 1
console.log(formatMoney(10)); // 10
console.log(formatMoney(100)); // 100
console.log(formatMoney(1000)); // 1,000
console.log(formatMoney(10000)); // 10,000
console.log(formatMoney(100000)); // 100,000
console.log(formatMoney(1000000)); // 1,000,000
console.log(formatMoney(35235235)); // 35,235,235