Vue技术之“格式化:正整数 和 正小数格式(两位小数)”

Vue技术之“格式化:正整数 和 正小数格式(两位小数)”

1.格式化正整数

/** 格式化正整数 */
const formatPositiveIntegerNumberMethod = (formatNumber: number) => {
  if (formatNumber === undefined && formatNumber === null) {
    return 1;
  }
  // 转换为字符串,过滤非数字字符
  const stringValue = String(formatNumber);
  // 正整数
  const filteredValue = stringValue.replace(/[^\d]/g, '');

  // 转换为数字并限制范围
  let numValue = parseInt(filteredValue) || 1;
  numValue = Math.max(1, numValue);

  // 更新数据
  return numValue;
}


2.正小数格式,两位小数

/** 正小数格式,两位小数 */
const handleDecimalInput = (row, field) => {
  // 1. 移除非数字和小数点
  let cleaned = row[field].replace(/[^\d.]/g, '');

  // 2. 只保留第一个小数点
  const parts = cleaned.split('.');
  if (parts.length > 2) {
    cleaned = parts[0] + '.' + parts.slice(1).join('');
  }

  // 3. 限制小数部分最多2位
  if (parts[1] && parts[1].length > 2) {
    parts[1] = parts[1].substring(0, 2);
    cleaned = parts.join('.');
  }

  // 4. 处理以小数点开头的情况
  if (cleaned.startsWith('.')) {
    cleaned = '0' + cleaned;
  }

  // 5. 如果是多个0开头,只保留一个0
  if (/^0+/.test(cleaned) && cleaned.length > 1 && !cleaned.startsWith('0.')) {
    cleaned = '0' + cleaned.substring(cleaned.indexOf('.') || cleaned.length);
  }

  // 更新数据
  row[field] = cleaned;
};

 




posted @ 2025-12-03 15:03  骚哥  阅读(4)  评论(0)    收藏  举报