The task is to create a function that adds commas as thousand separators.
The boilerplate code
function addComma(num) {
// your code here
}
Convert the number to string. Strings are easier to manipulate digit by digit. Then, split integer and decimal parts. Numbers after decimals don't require commas
const [integer, decimal] = String(num).split(".");
Handle negative integers
const sign = integer.startsWith("-") ? "-" : "";
const digits = sign ? integer.slice(1) : integer;
If the number is negative, the minus sign is saved in signand removed temporarily from digits.
Prepare variables for building the result
let result = ""
let count = 0
result is used to build the final string. Count counts the number of digits since the last comma. Add a comma after every 3 digits
for (let i = digits.length - 1; i >= 0; i--) {
result = digits[i] + result;
count++;
if (count % 3 === 0 && i !== 0) {
result = "," + result;
}
}
Add the sign and decimal afterwards
return sign + result + (decimal ? "." + decimal : "");
The final code
function addComma(num) {
// your code here
const[integer, decimal] = String(num).split(".");
const sign = integer.startsWith("-") ? "-" : "";
const digits = sign ? integer.slice(1) : integer;
let result = "";
let count = 0;
for(let i = digits.length -1; i >= 0; i--) {
result = digits[i] + result;
count++;
if(count % 3 === 0 && i !== 0) {
result = "," + result
}
}
return sign + result + (decimal ? "." + decimal : "")
}
That's all folks!
Top comments (0)