Javascript multiplication does not work properly for some numbers

I have strange behavior when multiplying JavaScript. I tried to multiply a number with 100. For example:

    > 9.5*100
    > 950
    > 9.95*100
    > 994.9999999999999
    > 9.995*100
    > 999.4999999999999
    > 9.9995*100
    > 999.9499999999999
    > 9.99995*100
    > 999.995
    > 9.999995*100
    > 999.9995
    > 9.9999995*100
    > 999.9999499999999
    > 9.99999995*100
    > 999.9999949999999
    > 9.999999995*100
    > 999.9999995
    > 9.9999999995*100
    > 999.99999995
    > 9.99999999995*100
    > 999.999999995
    > 9.999999999995*100
    > 999.9999999995
    > 9.9999999999995*100
    > 999.9999999999501
    > 9.99999999999995*100
    > 999.999999999995
    > 9.999999999999995*100
    > 999.9999999999994

I just want the numbers to multiply as follows

9.95*100
995.0 or 995
9.995*100
999.5
9.9995*100
999.95
9.9999995*100
999.99995

and NOT like this

> 9.995*100
> 999.4999999999999
> 9.9995*100
> 999.9499999999999
> 9.9999995*100
> 999.9999499999999

Is there any other way to multiply floating point numbers?

+4
source share
1 answer
var factor = 100;
var number = 9.95;
var b = number.toString().split('.'); 
var answer = b[0]*factor+b[1]*(factor/(Math.pow(10,b[1].length)));

This is one of the worst solutions, but it works: P

+4
source

Source: https://habr.com/ru/post/1615000/


All Articles