# Perl precision arithmetic, typcasting?

Thinking out loud here... just need some assurance and explanation.

I ran across code like this today.

\$number = 100.12;
\$number = int(\$number*100);
print "\$number\n";
\$number = \$number/100;
print "\$number\n";

Yields:
10012
100.12

as expected....

The problem: 1200.12
Yields:
120011
1200.11

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.

###### Who is Participating?

Commented:
Perl doesn't have an issue with floating point.  It's common to all programming languages.

int EXPR
int     Returns the integer portion of EXPR.  If EXPR is omitted, uses
\$_.  You should not use this function for rounding: one because
it truncates towards 0, and two because machine representations
of floating point numbers can sometimes produce
counterintuitive results.  For example, "int(-6.725/0.025)"
produces -268 rather than the correct -269; that's because it's
really more like -268.99999999999994315658 instead.  Usually,
the "sprintf", "printf", or the "POSIX::floor" and
"POSIX::ceil" functions will serve you better than will int().
0

Software EngineerCommented:
0

Author Commented:
Do you mean just checking if it has a decimal point?

Then if it does split on it and make sure the right side has two digits (add a zero if needed etc.) and cat the two parts back together... if it doesn't just tack on two zeros.
0

Author Commented:
Yes Sir. I was just realizing this fact. Same results in a c program...

Do you have a preference/recommendation??

I was just trying this and it seems to work consistently.

\$number = sprintf("%.0f", \$number)

Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.