Skip to content

Instantly share code, notes, and snippets.

@CITguy
Last active October 9, 2015 15:13
Show Gist options
  • Save CITguy/2f6111f50fc3a4f08b0e to your computer and use it in GitHub Desktop.
Save CITguy/2f6111f50fc3a4f08b0e to your computer and use it in GitHub Desktop.
String manipulation of currency to acquire penny amount
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