Skip to content

Instantly share code, notes, and snippets.

@thetitan
Last active March 22, 2017 22:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save thetitan/328a68da79f97d1ee27c5509cc91bf56 to your computer and use it in GitHub Desktop.
TitanFusion.net | Format number as US currency [JavaScript]
Format number as US currency
Format an unsigned integer or float to US currency string, e.g. $1,234,567.89.
1. Convert number to string.
2. If string contains period split at the period.
1234567.89 => string a) 1234567, string b) 89
3. If string a is 4 character or longer insert ',' every third character.
1234567 => 1,234,567
4. Concatenate string a and string b.
1,234,567 + 89 => 1,234,567.89
5. If requested, prepend '$' to number sting.
1,234,567.89 => $1,234,567.89
function formatCostNumber(amount, curSym) {
var unformattedNumber = amount || null;
var addSymbol = curSym || false;
var formattedNumber = "0";
var formatNumber = function(toFormat) {
if (toFormat.length >= 4) {
// Pars string in revers, track number of tiems looped
for (var i = toFormat.length, hops = 0, turns = 0; i >= 1; i--, turns++) {
// If moved 3 characters, insert comma
if (hops === 3 && toFormat.charAt(i) !== ',') {
toFormat = toFormat.substr(0, i) + ',' + toFormat.substr(i);
// Reset count since last ',' insertion, update string lenght
hops = 0;
i = toFormat.length - turns;
} else {
hops++;
}
}
}
return toFormat;
};
if (unformattedNumber !== null && typeof +unformattedNumber === 'number') {
// Convert number to string.
var numberString = unformattedNumber.toString();
// If string has a number split at '.' and format string before period
if (numberString.indexOf('.') !== -1) {
numberString = numberString.split('.');
formattedNumber = formatNumber(numberString[0]);
formattedNumber = formattedNumber + '.' + numberString[1];
} else {
formattedNumber = formatNumber(numberString);
}
}
// Add a currency symbol
return (addSymbol) ? '$' + formattedNumber : formattedNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment