Javascript math question...

Ichinisan

Lifer
Oct 9, 2002
28,298
1,236
136
I'm sure this is really basic, but I've been messing around with parseInt, toInt, parseFloat, toString, etc and can't figure out what's happening here.

alert(3*19.95);

"59.849999999999994"

It should be "59.85" ...so what's with the bad math?
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
I hate dealing with floating points in jscript. If I recall correctly I used this function to get the value I actually wanted:

Code:
alert(Round(3*19.95, 2));


function Round(value, decimals) {
    return (Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals));
}
 

Ichinisan

Lifer
Oct 9, 2002
28,298
1,236
136
I hate dealing with floating points in jscript. If I recall correctly I used this function to get the value I actually wanted:

Code:
alert(Round(3*19.95, 2));


function Round(value, decimals) {
    return (Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals));
}

It's strange that this is rounding at all when I'm not dividing and it's a fairly small number without a lot of precision. Anyway, I had to do something similar to:

((3*1995)/100)

I would expect the extra division operation to increase the chances of a math problem...but this works for some reason.
 
Sep 29, 2004
18,656
68
91
A computer does nto represent 0.95 as 0.95 in memory. It uses something like 0.9444449.

If you want your output to be human readable, use String.format().