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; };
* 博客文章部分截图及内容来自于学习的书本及相应培训课程,仅做学习讨论之用,不做商业用途。
* 如有侵权,马上联系我,我立马删除对应链接。
* 备注:王先生
* 我的网易邮箱:wzw_1314_520@163.com

浙公网安备 33010602011771号