Last active
March 26, 2021 03:14
-
-
Save airglow923/7d6ff685f976a3c29750c0636e033d54 to your computer and use it in GitHub Desktop.
Separate number with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
}; |
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
Usage:
Using decimal point:
Using decimal comma: