Sum with javascript returning wrong value

Asked

Viewed 226 times

0

I have some fields on my page and they have values, I take these values and we are, it turns out that the value goes wrong, as I take them from the DOM and end up coming as string, I convert into number, so instead of posting all the code here, comes out something like this:

var valor = parseInt("3.50");
console.log(valor + valor);

The value I expected was 7.00, but it returns me 6, IE, the sum seems to be wrong. Note: I am still learning

  • 2

    It’s not adding up wrong, you’re converting wrong. use parseFloat instead of parseint

  • parse int will return you only the integer value, without the decimal.

  • See the documentation

  • Wow, it worked, but it returns only the value like this: 7, there is a way to return equal to real?

  • 1

    parseInt, as the name says, transforms the value into INT, that is, an integer value. If it has a decimal value, it must convert to float, with the parseFloat.

  • @Otaviofagundes use the search field of the site, there are already related questions.

  • 1

    @Otaviofagundes would be like this: valor.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"}); remembering that valor has to be converted first.

  • Gave it right and still brought me the "R$" automatically, I did not know that javascript had this kind of thing

Show 3 more comments

1 answer

3


var valor = parseFloat("3.50");
console.log(valor + valor);

You are turning the string into Integer it will round down pattern, in case you can round up using Math.round() or how you are using Real number to use parseFloat()

Browser other questions tagged

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