Sum returns NaN for values above 999

4

I have a function that calculates subtotal + ascrescimo - desconto , however I was testing 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, "."));     
}

    
asked by anonymous 14.11.2018 / 17:34

1 answer

3

You need to do a replace before you remove all the dots from the number, and then make another replace that replaces the comma with a dot.

That's because if you just replace the comma with a dot, it will result in an invalid number when there are thousands separators. For example:

6.000,00 (seis mil) virará 6.000.00(?!)

With the two replaces:

6.000,00 (seis mil) virará 6000.00 ✔

To remove all possible points ( . ) of the number, you have to use a regular expression in replace (if you use only .replace(".", "") will remove only the first point):

.replace(/\./g, "")

The \. represents the point (the escape \ is used because the point alone has function inside the regular expression), and g (of global ) to get all occurrences.

Then another simple replace just to replace the comma:

.replace(",", ".")

Putting the two together, in order from left to right, is:

.replace(/\./g, "").replace(",", ".")
    
14.11.2018 / 17:55