Created
February 2, 2017 08:18
-
-
Save ifcanduela/72eaee090d7304a33a84398f7334c7cd to your computer and use it in GitHub Desktop.
A simple function to add thousands separators to a number.
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
function format_number(number) { | |
// split integer and decimal parts | |
var parts = ('' + number).split('.'); | |
var significand = parts[0]; | |
// check if there is a decimal part | |
var decimal = typeof parts[1] !== 'undefined' ? parts[1] : false; | |
// reverse the integer part | |
var reversed = (significand).split('').reverse().join(''); | |
// split the integer part in chunks of 3 max numbers | |
var chunks = reversed.match(/.{1,3}/g); | |
// join the chunks using the thousands separator and reverse the number again | |
var with_separator = chunks.join('.').split('').reverse().join(''); | |
// build the decimal part | |
var decimal_suffix = decimal ? (',' + decimal) : ''; | |
// return the full number | |
return with_separator + decimal_suffix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment