Created
September 17, 2013 08:23
-
-
Save nmenglund/6591506 to your computer and use it in GitHub Desktop.
Nordic number formatter; using , as decimal point when precision>0, and space as thousand separator otherwise (made for a pretty specific application)
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
| // Nordic number formatter; using , as decimal point when precision>0, | |
| // and space as thousand separator otherwise | |
| Number.prototype.formatNordic = function(precision) { | |
| precision = precision || 0; | |
| var rounded = Math.round(+this * Math.pow(10, precision)) / Math.pow(10, precision); | |
| var result = rounded.toString().replace(".",","); | |
| if (+precision > 0) { | |
| var pos = result.indexOf(','); | |
| if (pos == -1) | |
| result += "," + '0'.repeat(precision); | |
| else if ((pos+parseInt(precision)) <= result.length) | |
| result += '0'.repeat(precision - (result.length - pos - 1)); | |
| } else { | |
| // Thousand separator only when precision = 0 | |
| var result = rounded.toString(); | |
| var len = result.length; | |
| for (var x = 0; x < len; x++) | |
| { | |
| var offset = len - x - 1; | |
| if ((x % 3) == 0 && x > 0) | |
| result = result.splice(offset+1, 0, ' '); | |
| } | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment