Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: Round down to '.5' or '.0'

by Nkuvu (Priest)
on Oct 25, 2007 at 19:33 UTC ( [id://647254]=note: print w/replies, xml ) Need Help??


in reply to Re: Round down to '.5' or '.0'
in thread Round down to '.5' or '.0'

For some reason I was under the impression that the int function was doing rounding rather than truncating, so took a quick look at perldoc -f int, which mentioned that you should use POSIX::floor() rather than int. And sure enough, the code snippet above provides what I'd consider to be incorrect results for negative values. The OP doesn't mention if the input values will ever be negative, but consider the following:

#!/usr/bin/perl use strict; use warnings; use POSIX; my $num = -1.2; my $rounded_pos = (POSIX::floor($num*2))/2; my $rounded_int = (int $num*2)/2; printf "Rounded is %.1f for %f using POSIX\n", $rounded_pos, $num; printf "Rounded is %.1f for %f using int\n", $rounded_int, $num; __END__ Output: Rounded is -1.5 for -1.200000 using POSIX Rounded is -1.0 for -1.200000 using int

Simple change, and seems to be more robust. (Added: Although I may just be misinterpreting "rounding down" -- I think "down" is "in the negative direction" as opposed to "closer to zero". Hmm.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-23 07:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found