Sum of decimal values in Javascript

Asked

Viewed 823 times

0

When making sums of decimal values in Javascript (in the example with two decimal places). Sometimes the sum generates a result with 'n' decimal places other times not.

The question is:

Why does that happen?

How to standardize the result the way you want it.

Example.

document.getElementById("exemplo").innerHTML = 1.25+1.36
document.getElementById("exemplo2").innerHTML = 1.25+1.37
<div id="exemplo"></div>
<div id="exemplo2"></div>

2 answers

0


You can use Math to round the spool, or simply make the conversion to float.

Math.floor(1.25+1.36) //Resultado 2 , Valor arrendado para baixo

Math.ceil(1.25+1.36) //Resultado 3 , Valor arrendado para cima

parseFloat(1.25+1.37) //Resultado 2.62

-1

is very simple to solve

use the parseFloat()

document.getElementById("exemplo").innerHTML = parseFloat(1.25+1.37)
document.getElementById("exemplo2").innerHTML = parseFloat(1.25) + parseFloat(1.37)
<div id="exemplo"></div>
<div id="exemplo2"></div>

Browser other questions tagged

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