Unexpected behaviors with basic operations in JavaScript [duplicate]

0

I would like to know the reason for the strange behavior of JavaScript in subtractions with real numbers:

1.74 - 1.7
// retorna: 0.040000000000000036

I will explain the question better: I would like to know the reason for this characteristic and if there is any way to make the operation already avoiding it. I do not ask how to round or format the result. I'm new to JS and Stack, please do not stone me, thank you.

    
asked by anonymous 18.05.2018 / 02:07

1 answer

0

For us this calculation and the exact result of 0.4 seems so easy, but in JavaScript, all numbers are floating-point numbers of the IEEE 754 standard. Because of the binary nature of their encoding, some decimal numbers can not be represented with accuracy. This is analogous as the example of fraction 1/3 that can not be accurately represented with a decimal number with a finite number of digits. When you reach your storage limit, you'll need to round the last digit up or down.

Your first thought may be to try to round to the second decimal place. Unfortunately, internal JavaScript rounding functions are rounded to the nearest whole number only. However for your case and similar ones where the desired value is closest integer could be used yes and recommend toFixed (2)

resultado.toFixed(2);

I do not recommend, but: Still without using another framework or plugin for calculations, there is a slightly more precise way using only integers, as in the example would be multiplying by 100 the values would then have: 174 - 170, but it changes the perspective of representation of the value, where the decimals per the last 2 digits of the integer, even in this calculation if you do the result / 100 you will get the desired result: 0.4

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

    
18.05.2018 / 02:58