How to typecast in perl...

timjpriebe's picture

He has: 2,667 posts

Joined: Dec 2004

I'm trying to fix a problem in some Perl code, and part of it involves typecasting to an int, doing some calculations, then typecasting back to a float.

I've successfully typecast to an int by using int($thenumber). But how do I typecast back to a float or double?

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

You could change its printed representation to a float by using sprintf: [incode]sprintf("%f", int($thenumber));[/incode] and reuse the result. Unless [incode]use integer;[/incode] is in force, all arithmetic will be carried out in floating point anyway.

Details: perlnumber, perlop, sprintf.

Smiling

timjpriebe's picture

He has: 2,667 posts

Joined: Dec 2004

The big problem is happening when floating points aren't calculated correctly. Perl is saying at one point that 10.01 - 10 = .00999999999999997, or something like that. This is a financial calculation, and I don't really want to lose a penny on each transaction that happens like that. There's not many exactly like that, but still...

If I understand correctly what you're suggesting, I would end up getting back 0 still.

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

timjpriebe;211199 wrote: This is a financial calculation, and I don't really want to lose a penny on each transaction that happens like that. There's not many exactly like that, but still...

Ah, then you might want to follow the advice in perlop:

Quote:
Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

There may be a reliable third-party library to that effect, too.

timjpriebe;211199 wrote: The big problem is happening when floating points aren't calculated correctly. Perl is saying at one point that 10.01 - 10 = .00999999999999997, or something like that.

That is actually a 'correct' floating-point calculation. You can round the result to two decimal places like so: [incode]printf("%.2f", 10.01-10);[/incode]. (But note the preceding caveat!)

Smiling

They have: 1 posts

Joined: Jul 2010

This is an old post, so I'm writing an update to it so that you will know that there have been solutions in Perl for this for quite some time:

c:\temp>perl -e "use Math::BigFloat; my $a = Math::BigFloat->new(q|10.01|);
print $a->bsub(10);"
0.01

When looking for solutions in Perl, use search.cpan.org or perlmonks.org.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.