brick:为数字添加千位分隔符

134 阅读1分钟
function numFormat(num) {
  if (num == null) {
    return '0.00';
  }
  const numStr = num.toString();
  const isDecimal = numStr.indexOf('.');
  const integerPart = isDecimal < 0 ? numStr : numStr.split('.')[0];// 整数部分
  const decimal = isDecimal < 0 ? '00' : numStr.split('.')[1];// 小数部分
  const integerLen = integerPart.length;
  if (integerLen < 4) {
    return `${integerPart}.${decimal}`;
  }
  if (integerLen % 3 === 0) {
    const treatedInteger = integerPart.match(/\d{3}/g).join(',');
    return `${treatedInteger}.${decimal}`;
  }
  const treatedInteger = `${integerPart.substr(0, integerLen % 3)},${integerPart.match(/\d{3}/g).join(',')}`;
  return `${treatedInteger}.${decimal}`;
}