question/add-comma-to-number #46
Replies: 2 comments
-
方法二 正则 https://stackoverflow.com/a/2901298/5755195 /**
* @param {number} num
* @return {string}
*/
function addComma(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
console.log(addComma(1)) // '1'
console.log(addComma(1000)) // '1,000'
console.log(addComma(-12345678)) // '-12,345,678'
console.log(addComma(12345678.12345)) // '12,345,678.12345'
console.log(addComma(-.12345)) // '-0.1234' 相关解释可以看上面的链接,或者看 https://github.com/qdlaoyao/js-regex-mini-book 2.4.2 章节 |
Beta Was this translation helpful? Give feedback.
0 replies
-
方法一 普通方法 /**
* @param {number} num
* @return {string}
*/
function addComma(num) {
// your code here
let [number, decimal] = num.toString().split('.');
let str = '';
let i = number.length - 1;
let count = 0;
while (i >= 0) {
str = number[i] + str;
count++;
if (i > 0 && count % 3 === 0 && number[i -1] !== '-') {
str = ',' + str;
}
i--;
}
return decimal ? str + "." + decimal : str
}
console.log(addComma(-123.1234))
console.log(addComma(-.1234))
console.log(addComma(123456789))
console.log(addComma(123456789.1234)) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
question/add-comma-to-number
北美前端面试攻略
https://us-fe.github.io/question/add-comma-to-number.html
Beta Was this translation helpful? Give feedback.
All reactions