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

Re: Rounding off numbers

by salva (Abbot)
on Apr 20, 2006 at 14:29 UTC ( #544609=note: print w/replies, xml ) Need Help??


in reply to Rounding off numbers

use POSIX 'floor'; sub round { my $x = shift; floor($x + 0.5); }

You can use int instead of POSIX::floor if you don't need to round negative numbers. Anyway, read the docs for the int operator in perlfunc man page.

Replies are listed 'Best First'.
Re^2: Rounding off numbers
by Tanalis (Curate) on Apr 20, 2006 at 14:36 UTC
    .. though it's important to remember that simply casting a float to an int, thus:
    my $float = 2.744; my $int = int $float;
    results in the decimal part of the number simply being truncated, giving an integer value with the above example of 2, not 3, which is possibly not what's expected.

    Update: Although, of course, adding the 0.5 to the number solves the problem nicely. Didn't see that in the post until just now ..

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2020-12-02 09:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you use taint mode?





    Results (37 votes). Check out past polls.

    Notices?