分步解析逻辑:
- 去掉字符串的左右空格
- 检查是否为数字类型的字符串
- 分离整数和小数部分
- 去除数字前方的无用0
- 整数加千分位
- 把字符串原本的小数部分,重新拼接
function solution(s) {
let numStr = s.trim();//去掉左右空格
// 检查是否为有效的数字字符串(包括整数和小数)
if (isNaN(numStr) || !numStr) {
return "无效的字符串,不是数字";
}
// 获取整数部分和小数部分
const parts = numStr.split('.');
const integerPart = parts[0].replace(/^0+/, '') || '0'; // 去除整数部分的前导0,如果没有数字则设为'0'
const decimalPart = parts.length > 1 ? parts[1] : ''; // 如果存在小数部分,则保留原样
// 对整数部分添加千分位
const formattedIntegerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// 如果原数字有小数部分,则与格式化后的整数部分合并
return decimalPart ? `${formattedIntegerPart}.${decimalPart}` : formattedIntegerPart;
}
function main() {
console.log(solution("77134900601876576"))//第一版使用Number(str)去掉前方的0,会导致失去精度,返回77,134,900,601,876,580
console.log(solution("1294512.12412") === '1,294,512.12412');
console.log(solution("0000123456789.99") === '123,456,789.99');
console.log(solution("987654321") === '987,654,321');
}
main();
