Sum decimal places Javascript

Asked

Viewed 1,325 times

2

I have 3 Javascript variables:

valorUm = 2.8 //dois ponto oito
valorDois = 2.415 //dois mil quatrocentos e 15
valorLivre = 25 //vinte e cinco

What I need is:

valorUm + valorDois - valorLivre

this calculation returns me -19.785 and should return me 2392.8

I’m recovering input values:

valorUm = parseFloat(document.getElementById('ab').value.replace(",","."));
valorDois = parseFloat(document.getElementById('bc').value.replace(",","."));
valorLivre = parseFloat(document.getElementById('livre').value);
  • 1

    The account is right according to what you showed. The second number is 2 point 415 and there’s nothing thousand there. If you want a thousand then the number is 2415. The conversion seems to be ok. What may be wrong is that it is coming in a format that is not what you expect. How are the values being typed?

  • The values come from automatic calculations of the google maps api, I am recovering the values that comes '2.415 km', removing the text and calculating. But, these values are variable, can be 10.000 km or 2 km, IE, there is something that can do, so that regardless of the value returned to me comes an exact calculation?

  • How’s the shape in bc? The exact way the number gets?

  • in the input "2.415 km"

  • Got it, removed the points from bc, before giving replace. It worked blz

  • That’s what I said.

  • That’s right @bigown did what explained, vlw same guy.

Show 2 more comments

2 answers

2


According to the description of the comment the change needed should be this:

valorDois = parseFloat(document.getElementById('bc').value.replace(".", ""));

I put in the Github for future reference.

It’s still weird the other replace but if you think you’re right, I won’t question it. You don’t like to convert a number that contains text but it should work in this case. I find it strange for an API to send data this way to be consumed.

0

In my project it worked out that way:

    var quantidade = $('#quantidade').val().replace(",",".");

   var valorUnitario = $('#valor_unitario').val().replace(",",".");

   var valorTotal = parseFloat(valorUnitario) * parseFloat(quantidade);

   $('#valor_total').val(parseFloat(valorTotal));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.