Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript multiplication is not working properly for some numbers [duplicate]

I have got a strange behavior in JavaScript multiplication.I was trying to multiply the number with 100. Eg:

    > 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 be multiplied like this

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 method to multiply floating point Numbers?

like image 372
Able Johnson Avatar asked Nov 09 '15 06:11

Able Johnson


1 Answers

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 among the most worst solutions but works :P

like image 93
Minato Avatar answered Oct 13 '22 05:10

Minato