返回文章列表
·1 分钟阅读·

一个比较常用的数字格式化函数

背景

整理一个常用的数字格式化函数,具备常见的四舍五入、保留数位等功能

实现

import Decimal from 'decimal.js';

export const formatDigit = (
  digit?: number | string | null,
  options?: {
    nilResult?: string;
    emptyStringResult?: string;
    nanResult?: string;
    zeroResult?: string | false;
    precision?: number | false;
    thousandSeparator?: boolean;
  },
) => {
  const {
    nilResult = '-',
    emptyStringResult = nilResult,
    nanResult = nilResult,
    zeroResult = false,
    precision = false,
    thousandSeparator = false,
  } = options ?? {};

  if (digit === null || digit === undefined) {
    return nilResult;
  }
  if (digit === '') {
    return emptyStringResult;
  }

  try {
    const number = new Decimal(digit);

    if (number.isNaN()) {
      return nanResult;
    }
    if (number.eq(0) && zeroResult !== false) {
      return zeroResult;
    }

    let str: string;
    if (precision !== false) {
      str = number.toFixed(precision);
    } else {
      str = number.toString();
    }

    if (thousandSeparator) {
      return formatWithThousandSeparator(str);
    }
    return str;
  } catch (e) {
    return nanResult;
  }
};

const formatWithThousandSeparator = (str: string) => {
  const [intPart, decPart] = str.split('.');
  const intWithComma = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return decPart !== undefined ? `${intWithComma}.${decPart}` : intWithComma;
};