Question:
I need help to convert and add fields formatted as currency coming in this format "1,568.78"
I have a code that sums an array of installments and checks if it is equal to the total value of the invoice that I got here after several queries in user responses, and it works perfectly with whole numbers, but when I type the number formatted in reais it doesn't add up:
var quant = document.getElementsByName("valor[]");
function somarValores(){
var valor_fatura = parseInt(document.getElementById('valor_fatura').value);
var soma = 0;
var soma = [].reduce.call(quant, function (somatorio, el) {
return somatorio + parseInt(el.value, 10) || 0;
}, 0);
if(soma != valor_fatura){
alert('Valor não confere. Fatura='+valor_fatura+' - Parcelas='+soma+'');
return false;
}
}
I assume then that I have to convert the variables "quant" and "invoice_amount" to the format 1568.78 before calculating because as it is it rounds to whole numbers and disregards the cents causing an error in my validation
Answer:
Guys, the tips helped me a lot. I managed to solve it by removing the punctuation from the string and using parseFloat within the code itself so as not to end up with a huge code.
var quant = document.getElementsByName("valor[]");
function somarValores(){
var valor_fatura = parseFloat(document.getElementById('valor_fatura').value.replace('.','').replace(',','.'));
var soma = 0;
var soma = [].reduce.call(quant, function (somatorio, el) {
return somatorio + parseFloat(el.value.replace('.','').replace(',','.'), 10) || 0;
}, 0);
if(soma != valor_fatura){
var diferenca = soma - valor_fatura;
$("#lcto_mostraerro").append("Valor não confere. Há uma diferença de "+parseFloat(diferenca)+"");
return false;
}
}
First add parseFloat to the beginning of the string and strip the punctuation with replace ".replace('.','').replace(',','.')".
To give it an increment, I used .append to show the error inside a div instead of the alert