Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Best way to round a number.

by CountZero (Bishop)
on Oct 25, 2012 at 07:58 UTC ( #1000775=note: print w/replies, xml ) Need Help??

in reply to Best way to round a number.

Maybe not the "best" way, but very flexible: adjust the %rule hash to change the way the rounding will work based upon the last digit and the regex will do all the work (assuming you feed it a positive integer):
use Modern::Perl; my %rule = ( 0 => 0, 1 => -1, 2 => -2, 3 => 2, 4 => 1, 5 => 0, 6 => -1, 7 => -2, 8 => 2, 9 => 1, ); my @nums = 0..30; foreach (@nums) { print "in=$_"; s/(\d*(\d))/$1+$rule{$2}/e; say "\t rounded=$_"; }


A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

My blog: Imperial Deltronics

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1000775]
[choroba]: I don't even remember the beginning
[choroba]: someone told me to use perl instead of sed for something, and several years later, I'm developing a huge Tk application
[Discipulus]: choroba started in primary school to get some advantage in the future..

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2018-06-22 09:33 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (123 votes). Check out past polls.