-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
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
2020-03-07 千位计数格式 #2
Comments
|
|
function formatToThousands(number) {
if (!number) return 0
let str = number.toString()
// 处理最前部分
let len = str.length % 3,
res = `${str.slice(0, len % 3)}`
sub = str.slice(len % 3)
// 匹配余下部分
let reg = /[0-9]{1,3}/g,
tmp = null
while ((tmp = reg.exec(sub))) {
res += "," + tmp
}
return len % 3 ? res : res.slice(1)
}
console.log(formatToThousands(123456789)) // 123,456,789
console.log(formatToThousands(12)) // 12 |
function formatTohousands(number) {
} |
小数因为js机制会出现问题,哪一个大佬可以帮助解决一下
|
function formatToThousands(number) { |
function formatToThousands(number) {
number = number.toString();
if(/\./.test(number)){//存在小数点的情况
return number.replace(/\d(?=(\d{3})+\.)/g, "$&,");
}else{//不存在小数点的情况
return number.replace(/\d(?=(\d{3})+$)/g, "$&,");
}
}
console.log(formatToThousands(123456789)) |
@IskenHuang 哈哈我的答案被你抢注了。 |
|
|
|
/**
* 转换数字为千位计数格式
* @params {Number} number - 输入数字
* @renturn {String} 数字对应的千位格式的字符串
*/
function formatToThousands(number) {
if (!Number.isInteger(number)) return false;
var els = number.toString().split('');
var arr = []
for (var i = 0; i < els.length; i++) {
arr.push(els[i])
if ((i + 1) % 3 === 0 && i !== els.length - 1) {
arr.push(',')
}
}
return arr.join('')
}
console.log(formatToThousands(123456789)) // 123,456,789
console.log(formatToThousands(123456789.2233)) // false |
不强制要求使用正则,可以尽量使用正则实现,不太会正则的同学也可以顺便学习一下正则~
不需要考虑浏览器兼容性
The text was updated successfully, but these errors were encountered: