12/17 I am doing some simple subtraction on perl, and its generating
output like 8.39999999999998, how do I fix this? Thanks.
\_ Omg. I can't believe people ask this shit. Did you graduate
from Cal with a CS degree? You are a fucking disgrace.
\_ There are a significant number of non-CS majors here.
\_ There IS a significant number. Fucking disgraces, all
of you. Ugh. Go die.
\_ Wrong, dumbass. "A number of ___" is a plural noun.
"Are" is correct. Fucking disgrace.
\_ Agreed.
\_ you fix it by giving us example code or int($num + .5)
\_ I am doing something very simple, reading some numbers into
a variable, and subtract them. in my case, the number is
595 - 586.84, which should give me 8.16, but perl output
8.15999999999997, I need 8.16.... thanks...
\_ Like the poster below said, numbers like 8.16 can't be
represented exactly in binary, so you'll always get some
error. You can use $num = sprintf("%.2f", $num) to force
$num to have exactly two digits after the decimal point --
this also means that 8.5 will become 8.50, which is usually
what you want if you're dealing with money.
\_ And what is the precise binary representation of .84 pray
tell?
\_ Math::BigFloat
\_ If there's a specific precision you want, use fixed-point math or
round. |