Perl precision arithmetic, typcasting?
Posted on 2011-03-09
Thinking out loud here... just need some assurance and explanation.
I ran across code like this today.
$number = 100.12;
$number = int($number*100);
$number = $number/100;
The problem: 1200.12
So I think the only issue is the int(). I removed it and so far results are as expected. I'm just surprised that I found this issue, the code has been in use for a long time. So I'm concerned that there was a good reason for it and I'm creating another unforeseen problem. Also, want to make sure there's just not a better way to do it.
The value should always be a whole dollar or dollar.cents value, and should be enforced as such. Then stored without the decimal.
So (I guess) my question is what would you do?
The objective is to store the number without the decimal in it. The code snip is just an adhoc example. I mean you could do it without even using math. I know Perl has issues with floating-point arithmetic precision.