- Published on
Parsing Currency Amount from String in Javascript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Sometimes we might need to parse currency from a string.
A common use case would be the parsing amount from a bank statement.
For such use case, parseFloat could be a good fit.
The way the parseFloat works is that, it'll parse the number from the string and if it encounters any non-numeric characters (even a comma) it'll stop parsing and then return the amount that was parsed up to that point.
parseFloat('123.45 Cr') // 123.45
parseFloat('1,234.56 Cr') // NaN
And here is a helper function for that which takes care of removing non-numeric things from the string.
function parseCurrencyAmount(str) {
const cleanedStr = str.replace(/[^\d.-]/g, '');
const amount = parseFloat(cleanedStr);
return isNaN(amount) ? null : amount;
}
parseCurrencyAmount("$1,234.56"); // 1234.56
parseCurrencyAmount("INR 1,234.56 Cr"); // 1234.56
Happy parsing currency!