4
I have a function that calculates subtotal + ascrescimo - desconto
, but I went to test a value above 999 it returns NAN
.
//função para calcular o total da nota
function calcular() {
var soma1 = 0;
$(".subtotal01").each(function(indice1, item1){
var valor1 = parseFloat($(item1).val());
//console.log(valor);
if ( !isNaN( valor1 ) ) {
soma1 += valor1;
}
});
//pega o valor das desconto01 e caso haja substitue a virgula por ponto
var acrescimo01 = (document.getElementById("acrescimo01").value).replace(",", ".");
acrescimo01=Number(acrescimo01);
var desconto01 = (document.getElementById("desconto01").value).replace(",", ".");
desconto01=Number(desconto01);
soma1=(soma1).toFixed(2);
somatotal1=(soma1-desconto01+acrescimo01).toFixed(2);
ptotal1=((desconto01/soma1)*100).toFixed(2);
if(isNaN(ptotal1)) ptotal1 = 0;
//substitui separador decimal ponto por virgula
soma1=soma1.replace(".", ",");
somatotal1=somatotal1.replace(".", ",");
//a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
$("#total01").val((soma1).replace(/\B(?=(\d{3})+(?!\d))/g, "."));
document.getElementById('p1').innerHTML = '% ' + parseFloat(ptotal1);
$("#totalGeral01").val((somatotal1).replace(/\B(?=(\d{3})+(?!\d))/g, "."));
}
Before replacing the comma by a period, you need to remove all points before. It would be:
.replace(/\./g, "").replace(",", ".")
– Sam
Thus? var acrescimo01 = (Document.getElementById("acrescimo01"). value). replace("." , ""); acrescimo01 = (Document.getElementById("acrescimo01"). value). replace(",", "." ); acrescimo01=Number(acrescimo01);
– frodrigues
I changed the comment I made. Take a look. You have to use a regex to remove all the dots. But I don’t know if this is the cause of Nan, but it is necessary to do this before calculating.
– Sam
Our it worked out that I falter. Thank you very much, Ball Show.
– frodrigues
Blz. I will post a reply for future references. Abs!
– Sam