I am pretty new in JavaScript and JQuery and I am having a strange behavior with a simple mathematical sum into a JQuery function that retrieve numbers from some input field inside a JSP page (I can't put a JSFiddle because the values are take from jsp model object)
So, this is my JQuery function:
$("#variazioneUlterioreSaldoInput").bind('change keyup', function() {
console.log("VALUE CHANGED !!!");
var ulterioreSaldo = $("#variazioneUlterioreSaldoInput").val(); // Non ha separatori di migliaia o di decimanli quindi non devo eseguire replace
var saldo = $("#saldo").val().replace(/[^0-9,]/g, '').replace(",",".");
var anticipo = $("#anticipo").val().replace(/[^0-9,]/g, '').replace(",",".");
var totalePagamento = ulterioreSaldo + saldo + anticipo;
console.log("ulterioreSaldo: " + ulterioreSaldo );
console.log("ulterioreSaldo type: " + typeof ulterioreSaldo);
console.log("saldo: " + saldo);
console.log("saldo type: " + typeof saldo);
console.log("anticipo: " + anticipo);
console.log("anticipo type: " + typeof anticipo);
console.log("totalePagamento: " + totalePagamento);
console.log("totalePagamento type: " + typeof totalePagamento);
});
that retrieve and sum 3 values obtained from 3 differents input fields.
So for the values retrieved from the input tags having id="saldo" and id="anticipo" I apply a replace with 2 regex because these are strings that represent formatted number so before sum I have to obtain a plain number.
The problem is that when I perform the sum of these values by this line:
var totalePagamento = ulterioreSaldo + saldo + anticipo;
I obtain this wrong outout related to the sum: totalePagamento: 0.010.004499.48, this is the entire log into the FireBug Console.
VALUE CHANGED !!!
ulterioreSaldo: 0.01
ulterioreSaldo type: string
saldo: 0.00
saldo type: string
anticipo: 4499.48
anticipo type: string
totalePagamento: 0.010.004499.48
totalePagamento type: string
As you can see I have also printed the type of the retrieved objects and seems that are String and not Number so when I use the + operator these values are concatenated and not summed.
How can I correctly converts these values into Number and sum it?