Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active March 26, 2021 03:14
Show Gist options
  • Save airglow923/7d6ff685f976a3c29750c0636e033d54 to your computer and use it in GitHub Desktop.
Save airglow923/7d6ff685f976a3c29750c0636e033d54 to your computer and use it in GitHub Desktop.
Separate number with JavaScript
/* DISCLAIMER */
// This is all useless. Use Intl.NumberFormat instead.
const insertString = (string, index, newString) => {
return string.substr(0, index) + newString + string.substr(index);
};
const separateNumber = (number, separator = " ") => {
let string = String(number);
for (let i = string.length - 1, j = 1; i > 0; --i, ++j) {
if (j % 3 === 0) {
string = insertString(string, i, separator);
j = 0;
}
}
return string;
};
@airglow923
Copy link
Author

Use Intl.NumberFormat if your browser supports it. This provides localisation including decimal places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment