js实现 - 数字千分位加逗号,并四舍五入保留小数位

828 阅读1分钟

这个功能在某些场景下是非常重要的。在金融、数据分析、报表生成等领域,对数字进行格式化以提高可读性是非常常见且重要的。例如,展示大额货币金额、统计数据、百分比等都可以通过添加千分位逗号和保留适当的小数位数来提升用户体验和可视化效果。因此,其重要性使得它成为许多应用程序和系统中必不可少的功能之一。 下面是实现代码:

/**
 * @description: 数字千分位加逗号,并四舍五入保留小数位
 * @param {*} num 原始数字
 * @param {*} places 要保留的小数点后位数
 * @param {*} zeroFill 小数点后位数不足时是否需要补 0
 * @return {*}
 */
const toThousands = ( num:number, places = 2, zeroFill = false) => {
  if (typeof num === 'string') num = Number(num);
  if (typeof num !== 'number' || isNaN(num)) return;
  let numStr = String(num); // 数字字符串
  let [integer, decimal] = numStr.split('.'); // 整数部分,小数部分
  // 小数部分处理:四舍五入保留 places 位小数
  // 注意:不能直接使用 toFixed,toFixed 它是一个四舍六入五成双的诡异的方法(也叫银行家算法),"四舍六入五成双",最好别用,否则可能会出大问题!
  if (decimal && decimal.length > places) {
    const placesBase = Math.pow(10, places);
    num = Math.round(num * placesBase) / placesBase;
    numStr = String(num);
    decimal = numStr.split('.')[1];
  }
  decimal = decimal ? decimal : '';
  if (places > decimal.length && zeroFill) {
    const fillZeroCount = places - decimal.length;
    for (let i = 0; i < fillZeroCount; i++) {
      decimal += '0';
    }
  }
  // 整数部分处理
  let thousandsIntStr = '';
  while (integer.length > 3) {
    thousandsIntStr = ',' + integer.slice(-3) + thousandsIntStr;
    integer = integer.slice(0, integer.length - 3);
  }
  thousandsIntStr = integer ? integer + thousandsIntStr : thousandsIntStr;

  let result = decimal ? `${thousandsIntStr}.${decimal}` : thousandsIntStr;
  if (result.startsWith('-,')) result = result.replace('-,', '-');

  return result;
};