Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^3: Rounding off numbers

by Athanasius (Archbishop)
on Sep 13, 2014 at 09:34 UTC ( [id://1100478]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Rounding off numbers
in thread Rounding off numbers

Hello jmichae3, and welcome to the Monastery!

As swampyankee said, int($x + 0.5) correctly rounds $x to an integer, provided that $x is non-negative.

So, for example, if you have 2 * 4.5 and want to make sure this comes out to 9, use:

19:27 >perl -wE "my $x = 2 * 4.5; my $y = int($x + 0.5); say $y;" 9 19:28 >

This is useful, because for some values (and on some machines), a calculation like 2 * 4.5 might come out as 8.99999999998. But with the formula: add 0.5 and truncate, that’s OK now:

19:28 >perl -wE "my $x = 8.99999999998; my $y = int($x + 0.5); say $y; +" 9 19:30 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1100478]
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-23 06:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found