Created
November 18, 2015 22:53
-
-
Save pcrglennon/9c9009160faa7bb096af to your computer and use it in GitHub Desktop.
This file contains 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
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