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.
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.
– bfavaretto