JavaScript - Sum of comma separated numbers

Mohammed Imtiyaz Jul 25, 2018

In this tutorial we will learn to calculate the sum of input numbers on a webpage separated by comma using JavaScript.

Live Demo

 0.00

Usually the sum of input numbers is carried out by using a JavaScript function. Think of formatting the input numbers separated by comma before calculating the sum and obtaining the formatted output. i.e., formatting the input numbers first and then calculating sum of the formatted input numbers.

Let's try this out.

We need to write two JavaScript functions:

  • JavaScript function to format the input numbers.
  • JavaScript function to calculate the sum of formatted input numbers.

Format input numbers


//Using this script, the input numbers will be formatted.
$('.number').keyup(function(event) {

// skip for arrow keys
if (event.which >= 37 && event.which <= 40) {
	event.preventDefault();
}

$(this).val(function(index, value) {
	value = value.replace(/,/g, '');
		return numberWithCommas(value);
	});
});

//Replace numbers with comma separated numbers.
function numberWithCommas(x) {
	var parts = x.toString().split(".");
	parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	return parts.join(".");
}

Calculate the sum of formatted numbers


//Calculate the sum of two input integers.	
function Calculate() {
	var a, b;
	a = parseFloat(document.getElementById("input1").value.replace(/,/g, ""));
	if (isNaN(a) == true) {
	a = 0;
}
var b = parseFloat(document.getElementById("input2").value.replace(/,/g, ""));
	if (isNaN(b) == true) {
		b = 0;
}
document.getElementById("totalSpan").innerHTML = numberWithCommas(parseFloat(a + b).toFixed(2));
}