Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: int($x) gives strange result

by moritz (Cardinal)
on Aug 24, 2009 at 08:16 UTC ( [id://790769]=note: print w/replies, xml ) Need Help??


in reply to Re: int($x) gives strange result
in thread int($x) gives strange result

In general that's a very bad idea. If the number is larger, multiplying by 100.1 will severely skew the result:
$ perl -wle ' my $x = 123456.15; print +(int($x*100.1))/100;' 123579.6

So it turned 123456.15 into 123579.6 just to get rid of rounding errors - and produced errors which are about a thousand times larger.

Instead you can add (not multiply) a small constant before calling int:

$ $ perl -wle ' my $x = 1.15; print +(int($x*100 + 1e-8))/100;' 1.15

Depending on the range of the used numbers you'd have to think a bit more about the size of the small number you add.

Perl 6 projects - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^3: int($x) gives strange result
by SFLEX (Chaplain) on Aug 24, 2009 at 08:52 UTC
    ++moritz

    I was playing with it to the thousandth and found about the same "BAD" result:
    my $x = 1.159; print +(int($x*100.1))/100;

    What did the Pro-Perl programmer say to the Perl noob?
    You owe me some hair.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://790769]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-24 05:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found