5

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?

Able Johnson
  • 551
  • 7
  • 29
  • If you multiply only by 100, maybe consider to turn the number into string then move the dot to it's right location and then convert it again to number – Ziki Nov 09 '15 at 06:31
  • `b = (9.95).toString().split('.'); b[0]*100+b[1]*(100/(Math.pow(10,b[1].length)));` Most worst solution but works :P – Minato Nov 09 '15 at 06:40

1 Answers1

5
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

Minato
  • 4,383
  • 1
  • 22
  • 28