Created
October 10, 2013 14:10
-
-
Save Boldewyn/6919013 to your computer and use it in GitHub Desktop.
JS: format number the hard way
This file contains 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
/** | |
* format a number to look like "12.300 Mio." (german format) | |
* | |
* Spec: | |
* * numbers equal or larger than 100000 are suffixed with "Mio.". | |
* * three significant digits | |
* * dots after each 3 consecutive digits | |
* | |
* Why not use .toPrecision() alone? Because it might end up in | |
* "scientific notation" (1.23e9). Yeah, that makes sence, JS! | |
* | |
* @param Number num the number to format | |
* @return String the formatted representation | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision | |
*/ | |
function format_number(num) { | |
var append = ""; | |
if (num > 99999) { | |
append = " Mio."; | |
num /= 1e6; | |
} | |
return (+num.toPrecision(3)).toString() | |
.replace('.', ',') | |
.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + append; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment