Skip to content

Instantly share code, notes, and snippets.

@xheuz
Last active April 2, 2020 20:04
Show Gist options
  • Save xheuz/f97f92d0dec09fdd543554a0a8c484ae to your computer and use it in GitHub Desktop.
Save xheuz/f97f92d0dec09fdd543554a0a8c484ae to your computer and use it in GitHub Desktop.
A javascript solution to add thousands separator to numbers
export const numberWithThousandsSeparator = (
number,
decimalDigits = 0,
separator = ",",
decimalSeparator = "."
) => {
let isNegative = false;
if (!number) return number;
if (number >= 0 && number < 1000)
return number.toFixed(decimalDigits).toString();
if (number < 0) isNegative = true;
number = Math.abs(number);
const [integer, decimals] = number
.toFixed(decimalDigits)
.toString()
.split(".");
let numberArray = integer.split("");
let numberOfCommas =
numberArray.length % 3 === 0
? Math.floor(numberArray.length / 3) - 1
: Math.floor(numberArray.length / 3);
while (numberOfCommas) {
// This assign the comma from left to right
let position = numberArray.length - 3 * numberOfCommas;
numberArray.splice(position, 0, separator);
numberOfCommas -= 1;
}
return `${isNegative ? "-" : ""}${numberArray.join("")}${
decimals ? `${decimalSeparator}${decimals}` : ""
}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment