Last active
October 9, 2015 15:13
-
-
Save CITguy/2f6111f50fc3a4f08b0e to your computer and use it in GitHub Desktop.
String manipulation of currency to acquire penny amount
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
function currencyToPennies (currency) { | |
// ensure string | |
var strCurrency = currency.toString(); | |
// ignore any character that's not part of a number | |
var wholeAmount = strCurrency.replace(/[^0-9.]/g, ''); | |
// locate decimal | |
var decimalIndex = wholeAmount.indexOf('.'); | |
var normalizedAmount; | |
if (decimalIndex > 0) { | |
// truncate to 2 decimal places | |
normalizedAmount = wholeAmount.slice(0, decimalIndex + 3); | |
} else { | |
// whole number, concat decimal value | |
normalizedAmount = wholeAmount + '.00'; | |
} | |
// drop decimal (leaves total pennies) | |
var pennyAmount = normalizedAmount.replace(/[^0-9]/g, ''); | |
// Negative Number format | |
if (strCurrency.indexOf('(') > -1 && strCurrency.indexOf(')') > -1) { | |
pennyAmount *= -1; | |
} | |
return parseInt(pennyAmount); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment