5
I need help to convert and add formatted currency fields coming in this format "1.568,78"
I have a code that sums an array of parcels and checks if it is equal to the total value of the invoice that I got here after several queries in user replies, and works perfectly with integers, but when I type the number formatted in real it does not 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 value" to the format 1568.78 before calculating because as it is it rounds to whole numbers and disregards the cents causing error in my validation
I started writing an answer but then I saw the size of the responsibility. Basically, you’ll have to do a function that replaces the commas with dots and vice versa and then use parseFloat. The problem is that Javascript does not have a "replaceAll". Substitutes include using regular expressions, but this brings the danger of entries containing metacharacters (special regular expression characters). Then you would also have to do a pretreatment of the entrance to avoid this. That is, it will take a little work. If you follow this tip, post here to us your solution. :)
– Pablo Almeida