Skip to content

Instantly share code, notes, and snippets.

@Boldewyn
Created October 10, 2013 14:10
Show Gist options
  • Save Boldewyn/6919013 to your computer and use it in GitHub Desktop.
Save Boldewyn/6919013 to your computer and use it in GitHub Desktop.
JS: format number the hard way
/**
* 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