Skip to content

@utilslib/core/formatPrice


格式化价格,添加千位分隔符并保留指定的小数位数。


formatPrice

函数签名

typescript
function formatPrice(value: string | number, decimalPlaces: number = -1): string

描述

格式化价格,添加千位分隔符并保留指定的小数位数。

参数

参数名类型可选默认值描述
valuestring | number--
decimalPlacesnumber-1-

返回值

string

点击查看源码
js
/**
 * 格式化价格,添加千位分隔符并保留指定的小数位数。
 *
 * @param {string | number} value - 要格式化的价格。
 * @param {number} decimalPlaces - 可选的小数位数,默认为不处理小数位数。
 * @returns {string} 格式化后的价格。
 */
export function formatPrice(value, decimalPlaces = -1) {
  const numberValue = typeof value === "number" ? value : parseFloat(value);
  if (isNaN(numberValue)) value.toString();
  const options = {
    minimumFractionDigits: decimalPlaces >= 0 ? decimalPlaces : 0,
    maximumFractionDigits: decimalPlaces >= 0 ? decimalPlaces : 2,
  };
  return numberValue.toLocaleString(undefined, options);
}
ts
/**
 * 格式化价格,添加千位分隔符并保留指定的小数位数。
 *
 * @param {string | number} value - 要格式化的价格。
 * @param {number} decimalPlaces - 可选的小数位数,默认为不处理小数位数。
 * @returns {string} 格式化后的价格。
 */
export function formatPrice(
  value: string | number,
  decimalPlaces: number = -1,
): string {
  const numberValue = typeof value === "number" ? value : parseFloat(value);
  if (isNaN(numberValue)) value.toString();
  const options = {
    minimumFractionDigits: decimalPlaces >= 0 ? decimalPlaces : 0,
    maximumFractionDigits: decimalPlaces >= 0 ? decimalPlaces : 2,
  };

  return numberValue.toLocaleString(undefined, options);
}

如有错误,请提交issue :::