DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 104

The task is to create a function that adds commas as thousand separators.

The boilerplate code

function addComma(num) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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(".");
Enter fullscreen mode Exit fullscreen mode

Handle negative integers

const sign = integer.startsWith("-") ? "-" : "";
const digits = sign ? integer.slice(1) : integer;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
    }
  }
Enter fullscreen mode Exit fullscreen mode

Add the sign and decimal afterwards

return sign + result + (decimal ? "." + decimal : "");
Enter fullscreen mode Exit fullscreen mode

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 : "")
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)