Javascript – Parsing float

ShaunJavascriptLeave a Comment

Javascript development


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));

// "12,000.20"

// "12,000.20"

// "562,000.34"



Leave a Reply

Your email address will not be published.