How to typecast in perl...
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 posted this at 17:17 — 30th November 2006.
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.
timjpriebe posted this at 06:12 — 1st December 2006.
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.
Tim
http://www.tandswebdesign.com
Abhishek Reddy posted this at 11:33 — 1st December 2006.
He has: 3,348 posts
Joined: Jul 2001
Ah, then you might want to follow the advice in perlop:
There may be a reliable third-party library to that effect, too.
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!)
InfiniteSilence posted this at 05:47 — 30th July 2010.
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.