Last active
November 8, 2020 18:11
-
-
Save benhodgson87/becf5884a53d90f86b6e to your computer and use it in GitHub Desktop.
DecimalFormat Currency Formatting
This file contains hidden or 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
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use: