Strange behavior in Javascript

Asked

Viewed 81 times

1

This question is more out of curiosity, I’ve already answered the problem in my code.

I made a money mask using javascript, it was working perfectly, until I entered the value 4.9.

Debugging the code found that the problem was multiplying the value 4.9 by 100, the result of this multiplication gave:

490.00000000000006

What made my mask "bugger".

Other values like 4.8 the result is shown correctly, like:

480

Follow the code below to illustrate:

alert(4.9*100);

//Sem problemas
alert(4.8*100);

//Outro exemplo mais grave
alert(4.6*100);

My question is this, why is there this strange behavior in Javascript? I did the same multiplication using php and it worked normally.

And for those who had the same problem and just want to solve, I solved it in the following way:

var valor = 4.9;
resultado = (valor  * 100).toFixed(2);
alert(valor);

var valor = 4.6;
resultado = (valor  * 100).toFixed(2);
alert(valor);

  • 2

    Briefly, calculations with floating point numbers are not exact

  • 3

    Would that be? https://answall.com/questions/14728/realizes%C3%A7%C3%A3o-de-floating-point-in-javascript-with-precis%C3%A3o-absolute

  • 2

    this is an old known number rounding problem in javascript, has this interesting question in the OS in English: how-to-Deal-with-floating-point-number-Precision-in-javascript

1 answer

1

This has to do with the IEEE regulation for binary representation for floating point number. A good way out is also to work with integers, multiplying your coin by 100 before operating and then dividing by 100 to see with the cents after the point.

Browser other questions tagged

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