Skip to content

Instantly share code, notes, and snippets.

@benhodgson87
Last active November 8, 2020 18:11
Show Gist options
  • Save benhodgson87/becf5884a53d90f86b6e to your computer and use it in GitHub Desktop.
Save benhodgson87/becf5884a53d90f86b6e to your computer and use it in GitHub Desktop.
DecimalFormat Currency Formatting
Number.prototype.currency = function (format) {
var amt = this, neg;
// If no formatting string supplied
// or amount is not a number, return as is
if (!format || isNaN(amt)) return amt;
// Extract placeholders from format string
var formFig = format.match(/\#(.*)\#/g).pop();
// Is number negative?
if (amt < 0) {
neg = true;
amt = (amt * -1);
}
// Remove any decimals
amt = amt.toString().replace(/[ ,.]/, '');
// Split and flip the numbers and format
var formArr = formFig.split('').reverse(),
amtArr = amt.split('').reverse();
// Add leading zeros to small amounts, if there's a separator in last 3 digits
if (amtArr.length < 3 && format.slice(-3).match(/[ ,.]/)) {
while (3 - amtArr.length) {
amtArr.push('0');
}
}
// Loop through the formatting, and look for separators
// Only get separators that fit within the length of the amount
for (var i = 0; i < amtArr.length; ++i) {
// If we find a matching separator, splice it into the amount in the same place
if (/[ ,.]/.test(formArr[i])) {
amtArr.splice(i, 0, formArr[i]);
}
}
// Flip the amount back in the right direction, and rejoin
var amount = amtArr.reverse().join('');
// Handle Negatives (minus or parentheses)
if (!neg) format = format.replace(/[\-\(\)]/gi, '');
// Merge the amount back with the currency symbols
var money = format.replace(/\#(.*)\#/g, amount);
return money;
};
@benhodgson87
Copy link
Author

To use:

var price = 123456;

price.currency('-£###,###,###.##'); // Returns: £1,234.56
price.currency('-###,###,###円'); // Returns: 123,456円

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment