Created
June 11, 2013 12:05
-
-
Save Rich-Harris/5756323 to your computer and use it in GitHub Desktop.
Add comma separators (e.g. `addCommaSeparators(1234567) === '1,234,567'`)
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 ( 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