Last active
August 29, 2015 14:26
-
-
Save carbonphyber/44a85bde6d7f99ea7501 to your computer and use it in GitHub Desktop.
A function to parse a USD currency
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
"use strict"; | |
var tests = { | |
"$0.41": 0.41, | |
"$12,345.67": 12345.67, | |
"$1m": 1000000, | |
"$32b": 32000000000, | |
"$0.2t": 200000000000 | |
}; | |
var currencyToFloat = function (inputString) { | |
// clean a dollar sign and any leading+trailing spaces | |
var inputString = inputString.replace(/^\s*\$\s*/g, '').replace(/^\s+|\s+$/g, '').replace(',', ''); | |
// trailing "m" means 1.0x10^6 | |
if(inputString.match(/m$/i)) { | |
return parseFloat(inputString) * 1000000; | |
// trailing "m" means 1.0x10^9 | |
} else if(inputString.match(/b$/i)) { | |
return parseFloat(inputString) * 1000000000; | |
// trailing "m" means 1.0x10^12 | |
} else if(inputString.match(/t$/i)) { | |
return parseFloat(inputString) * 1000000000000; | |
} | |
return parseFloat(inputString); | |
} | |
for (var i in tests) { | |
var this_result = currencyToFloat(i); | |
if(this_result !== tests[i]) { | |
console.log('failed: ', i, '; expected: ', tests[i], '; received: ', this_result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment