vue3+elementplus 去除小数点后多余的0公用函数

发布时间 2023-09-22 12:46:22作者: 城南城南

vue3+elementplus 去除小数点后多余的0公用函数

export function removeTrailingZeros(value) {
  // 尝试将值转换为数字
  const numericValue = parseFloat(value);

  // 检查是否成功转换为数字
  if (!isNaN(numericValue) && typeof numericValue === 'number') {
    // 将数字转换为字符串
    const stringValue = numericValue.toString();
    
    // 使用正则表达式去除小数点后多余的0
    const formattedValue = stringValue.replace(/(\.\d*?[1-9])0+$/, '$1');
    
    // 如果去除0后,字符串以小数点结尾,则去掉小数点
    return formattedValue.endsWith('.') ? formattedValue.slice(0, -1) : formattedValue;
  }
  
  // 如果无法转换为数字,返回原始值
  return value;
}