We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
要求:使用正则和非正则两种方式实现
评论区大神们,欢迎附上正则版~
// 法1:toLocaleString // 浏览器提供该 api 对数字进行格式化,不过对于小数的处理使用的是四舍五入 let num = 1234567; console.log(num.toLocaleString('en-US')); // 1,234,567 num = 12345.6785; console.log(num.toLocaleString('en-US')); // 12,345.679 // 法2:数组操作 function format(num) { if (typeof num !== 'number') return num; const [ first, last ] = (num + '').split('.'); const flen = first.length; const tmp = first.split('').reverse().reduce((res, n, i) => { if ((i + 1) % 3 === 0 && i !== flen - 1) res.push(n, ','); else res.push(n); return res; }, []).reverse().join(''); return last ? tmp + '.' + last : tmp; } // 法3:递归 function format(num) { if (typeof num !== 'number') return num; const [first, last] = (num + '').split('.'); function run(s) { if (s.length <= 3) return s; return run(s.slice(0, -3)) + ',' + s.slice(-3); } return last ? run(first) + '.' + last : run(first); } console.log(format(123456)); // 123,456 console.log(format(1234567)); // 1,234,567 console.log(format(12345.6785)); // 12,345.6785 console.log(format(123456.78)); // 123,456.78
The text was updated successfully, but these errors were encountered:
如果整数部分的长度是3的整数倍,计算出来的字符串首位会是 ‘’,‘’需要判断一下 console.log(format(123456)); // ,123,456
console.log(format(123456)); // ,123,456
Sorry, something went wrong.
@zhhyang 感谢纠正,已改
正则版:
function format(num){ return String(num).replace(/(\d)(?=(\d{3})+(?!\d))/g,'$1,') }
No branches or pull requests
格式化数字
要求:使用正则和非正则两种方式实现
评论区大神们,欢迎附上正则版~
The text was updated successfully, but these errors were encountered: