Unexpected behavior with basic Javascript operations

Asked

Viewed 39 times

0

I would like to know the reason for the behavior, in my view strange, Javascript in subtractions with real numbers:

1.74 - 1.7
// retorna: 0.040000000000000036

I explain the question better: I would like to know why this feature and if there is any way to do the operation already avoiding. I don’t ask how to round or format the result. I’m new to JS and Stack, please don’t stone me, thank you.

  • Welcome to the site, I hope you didn’t feel stoned. Marking duplicate is nothing against your question. The idea of this resource here is to create a web of related content to help people find the answers. Read the linked contents in the top yellow box, see if they resolve your question.

1 answer

0

This calculation and the exact result of 0.4 seems so easy to us, but in Javascript, all numbers are floating point numbers of the IEEE 754 standard. Due to the binary nature of its encoding, some decimal numbers cannot be represented with perfect precision. This is analogous to the example of the 1/3 fraction that cannot be accurately represented with a decimal number with a finite number of digits. When you reach your storage limit, you will need to round the last digit up or down.

Your first thought may be to try rounding to the second decimal place. Unfortunately, Javascript’s internal rounding functions are rounded only to the nearest integer. However, for your case and similar cases where the desired integer value is closest, it could be used yes and I recommend toFixed(2)

resultado.toFixed(2);

I don’t recommend it, but: Still without using another framework or plugin for calculations, there is a slightly more accurate way using numbers only integers, as in the example would multiply by 100 the values then would have: 174 - 170, but changes the perspective of value representation, where the decimal percentile at the last 2 digits of the integer itself, still in this calculation the result / 100 will get the desired result: 0.4

Obs. It worked for this case and many others. But of course, this cannot be 100% guaranteed because division and multiplication can result in inaccurate values.

Browser other questions tagged

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