Skip to content

Instantly share code, notes, and snippets.

@myersjustinc
Last active September 29, 2015 11:47
Show Gist options
  • Save myersjustinc/1595911 to your computer and use it in GitHub Desktop.
Save myersjustinc/1595911 to your computer and use it in GitHub Desktop.
JS number formatting (thousands and uniform decimal places)
var formatNumber = function( value, decimalPlaces, alwaysDecimalize ) {
// Set default decimal formatting values if undefined
// decimalPlaces defaults to 0
// Sets the number of places after the decimal point, if necessary
// alwaysDecimalize defaults to false
// If true, always shows a decimal and the set number of decimal
// places, even for integral values (useful with currency values)
decimalPlaces = typeof decimalPlaces === 'undefined' ? 0 : decimalPlaces;
alwaysDecimalize = (typeof alwaysDecimalize === 'undefined' ? false :
alwaysDecimalize);
if ( value === Number.POSITIVE_INFINITY ) {
return '\u221e';
} else if ( value === Number.NEGATIVE_INFINITY ) {
return '-\u221e';
} else if ( isNaN( value ) ) {
return 'N/A';
}
var commasToAdd,
decimalPart = '',
firstComma,
i,
signPart = '',
wholePart = Math.floor( Math.abs( value ) ) + '', // Coerce to string.
withCommas = wholePart,
withCommasLength = withCommas.length;
// Add a negative sign if the number is negative.
if ( value < 0 ) {
signPart = '-';
}
// Find the part after the decimal point.
if ( alwaysDecimalize || value % 1 !== 0 ) {
decimalPart = ( Math.abs( value ) % 1 ).toFixed( decimalPlaces );
decimalPart = decimalPart.substring( 1 ); // Remove leading zero.
}
// Figure out how many commas we need to add.
commasToAdd = Math.floor( withCommasLength / 3 );
if ( withCommas.length % 3 === 0 ) {
commasToAdd -= 1;
}
// Now that we know how many commas to add, add them!
for ( i = 0; i < commasToAdd; i++ ) {
firstComma = withCommas.indexOf( ',' );
if ( firstComma >= 0 ) {
withCommas = withCommas.substring( 0, firstComma - 3 ) +
',' + withCommas.substring( firstComma - 3);
} else {
withCommasLength = withCommas.length;
withCommas = withCommas.substring( 0, withCommasLength - 3 ) +
',' + withCommas.substring( withCommasLength - 3 );
}
}
return signPart + withCommas + decimalPart;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment