Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created June 11, 2013 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/5756323 to your computer and use it in GitHub Desktop.
Save Rich-Harris/5756323 to your computer and use it in GitHub Desktop.
Add comma separators (e.g. `addCommaSeparators(1234567) === '1,234,567'`)
(function ( global ) {
'use strict';
var addCommaSeparators = function ( num, precision ) {
var integer, decimal, remaining, result, lastThree;
integer = Math.floor( num );
decimal = num - integer;
precision = precision || 1;
result = '';
remaining = '' + integer;
while ( remaining.length > 3 ) {
// take the last three
lastThree = remaining.substr( -3 );
result = ( ',' + lastThree + result );
remaining = remaining.substr( 0, remaining.length - 3 );
}
result = remaining + result;
if ( decimal ) {
result += ( '' + decimal.toFixed( precision ) ).substring( 1 );
}
return result;
};
// export as CommonJS module...
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = addCommaSeparators;
}
// ...or as AMD module...
else if ( typeof define !== 'undefined' && define.amd ) {
define( function () { return addCommaSeparators; });
}
// ...or as browser global
else {
global.addCommaSeparators = addCommaSeparators;
}
}( this ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment