Javascript
Parse Float with commas
When dealing with calculations around pricing, it is important to ensure when usingĀ parseFloat in JavaScript that it doesn’t malform the result.
The function below checks your number if it contains commas, strips them out, parses float to 2 decimal places, then adds the commas back in:
var parseFloatWithCommas = function(val) { if (typeof val === 'number') { val = val.toString(); } var numberWithCommas = function(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }; return numberWithCommas(parseFloat(val.replace(',', '')).toFixed(2)); }; parseFloatWithCommas('12,000.2'); // "12,000.20" parseFloatWithCommas('12000.2'); // "12,000.20" parseFloatWithCommas(562000.340); // "562,000.34"