lishengzxc / bblog

My Blog
https://github.com/lishengzxc/bblog/issues
178 stars 8 forks source link

JS货币格式化 #15

Open lishengzxc opened 8 years ago

lishengzxc commented 8 years ago

在日常开发中遇到一个数字千分位格式化,所谓的数字千分位格式化,即从个位数起,每三位之间加一个逗号。例如“10,000”

通过google和自己的实践收集并整理了一下方法。

//1.
function toThousands(num) {
    var result = [ ], counter = 0;
    num = (num || 0).toString().split('');
    for (var i = num.length - 1; i >= 0; i--) {
        counter++;
        result.unshift(num[i]);
        if (!(counter % 3) && i != 0) { result.unshift(','); }
    }
    return result.join('');
}

方法一的执行过程就是把数字转换成字符串后,打散为数组,再从末尾开始,逐个把数组中的元素插入到新数组(result)的开头。每插入一个元素,counter就计一次数(加1),当counter为3的倍数时,就插入一个逗号,但是要注意开头(i为0时)不需要逗号。最后通过调用新数组的join方法得出结果。

//2.
function toThousands(num) {
    var result = '', counter = 0;
    num = (num || 0).toString();
    for (var i = num.length - 1; i >= 0; i--) {
        counter++;
        result = num.charAt(i) + result;
        if (!(counter % 3) && i != 0) { result = ',' + result; }
    }
    return result;
}

方法二是方法一的改良版,不把字符串打散为数组,始终对字符串操作。

//3.
function toThousands(num) {
    var num = (num || 0).toString(), re = /\d{3}$/, result = '';
    while ( re.test(num) ) {
        result = RegExp.lastMatch + result;
        if (num !== RegExp.lastMatch) {
            result = ',' + result;
            num = RegExp.leftContext;
        } else {
            num = '';
            break;
        }
    }
    if (num) { result = num + result; }
    return result;
}

通过正则表达式循环匹配末尾的三个数字,每匹配一次,就把逗号和匹配到的内容插入到结果字符串的开头,然后把匹配目标(num)赋值为还没匹配的内容(RegExp.leftContext)。此外,还要注意:

//4
function toThousands(num) {
    var num = (num || 0).toString(), result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return result;
}

截取末尾三个字符的功能可以通过字符串类型的slice、substr或substring方法做到。这样就可以避免使用正则表达式。(正解)

//5
function toThousands(num) {
    var num = (num || 0).toString(), temp = num.length % 3;
    switch (temp) {
        case 1:
            num = '00' + num;
            break;
        case 2:
            num = '0' + num;
            break;
    }
    return num.match(/\d{3}/g).join(',').replace(/^0+/, '');
}

先把数字的位数补足为3的倍数,通过正则表达式,将其切割成每三个数字一个分组,再通过join方法添加逗号,最后还要把补的0移除。

//6
function toThousands(num) {
    return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}

正则表达式正向前瞻,(javascript是不支持后瞻)

总结:方法四最后,循环最少,没有正则性能肯定是最好的了。

参考 http://www.cnblogs.com/rubylouvre/archive/2010/03/09/1681222.html

kbyyd24 commented 8 years ago

How to reply comments?

lishengzxc commented 8 years ago

@kbyyd24

kbyyd24 commented 8 years ago

@lishengzxc soga

jzoe commented 7 years ago

@lishengzxc 方法4并没有对小数点进行处理

jsm1003 commented 6 years ago

Number.toLocalString()这个方法就可以啊,原生的格式化货币方法

LeeHao12 commented 6 years ago
// 方法四 支持 小数版本
export function toThousandsString(number: number | string) {
  const splitNumber = number.toString().split('.')
  let integer = splitNumber[0]
  const decimal = splitNumber[1] || ''

  let result = ''
  while (integer.length > 3) {
    result = ',' + integer.slice(-3) + result
    integer = integer.slice(0, integer.length - 3)
  }
  if (integer) {
    result = integer + result
  }

  if (decimal === '') {
    return result
  }

  return result + '.' + decimal
}
zhukejin commented 5 years ago
(123456789).toLocaleString('en-US')  // 1,234,567,890
new Intl.NumberFormat().format(1234567890) // 1,234,567,890
fengyun2 commented 5 years ago

Number.toLocalString()这个方法就可以啊,原生的格式化货币方法

好像ie9下,就算是整型数据也会保留两位小数点