Skip to content

Instantly share code, notes, and snippets.

@pcrglennon
Created November 18, 2015 22:53
Show Gist options
  • Save pcrglennon/9c9009160faa7bb096af to your computer and use it in GitHub Desktop.
Save pcrglennon/9c9009160faa7bb096af to your computer and use it in GitHub Desktop.
var currencySymbols = {
USD: "$"
};
var delimiters = {
USD: ","
};
var separators = {
USD: "."
};
function getDollars(currency, amountString) {
var delimiter = delimiters[currency];
var dollars = amountString.match(new RegExp(`^(?:\\D*)([0-9${delimiter}]+)`));
dollars = (dollars && dollars[1]) ? dollars[1] : "0";
dollars = dollars.replace(new RegExp(`${delimiter}`, 'g'), '');
return parseInt(dollars, 10);
}
function getCents(currency, amountString) {
var separator = separators[currency];
var cents = amountString.match(new RegExp(`[${separator}]([0-9]{0,2}).*$`));
cents = (cents && cents[1]) ? cents[1] : "0";
return parseInt(cents, 10);
}
function validateFormat(currency, amountString) {
var symbol = currencySymbols[currency],
delimiter = delimiters[currency],
separator = separators[currency];
var regex = new RegExp(`^[${symbol}]{0,1}[0-9${delimiter}]+[${separator}]{0,1}[0-9]*$`);
return regex.test(amountString);
}
function toCents(currency, amountString) {
var dollars = getDollars(currency, amountString);
var cents = getCents(currency, amountString);
return (dollars * 100) + cents;
}
function validateFormat(currency, amountString) {
return validateFormat(currency, amountString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment