Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

How do I round a number?

( #24335=categorized question: print w/ replies, xml ) Need Help??
Contributed by Anonymous Monk on Jul 25, 2000 at 23:48 UTC
Q&A  > math


Answer: How do I round a number?
contributed by ryanus

I would use Math::Round. It is easy to use. For example:

use Math::Round; print nearest(.01, 1.555);
prints '1.56'.

Answer: How do I round a number?
contributed by fundflow

The guy asked to round a number, the simplest way is (my highschool teacher would be proud now..): $rounded = int ( $orig + 0.5 )
This approach floors any decimal portion less than 0.5, and rounds up (in value) any decimal portion greater than .5. That means the following:

1.1 rounds to 1.0. 1.5 rounds to 2.0. -1.1 rounds to 1.0. -1.5 rounds to 1.0.
Answer: How do I round a number?
contributed by buckaduck

For scientific applications requiring the use of significant figures ("sig figs"), I strongly recommend the Math::SigFigs module. Unfortunately, the CPAN testers still haven't cleared it for Windows clients, though...

use Math::SigFigs; print FormatSigFigs($number, $digits);
Answer: How do I round a number?
contributed by jlistf

POSIX probably has an appropriate routine that'll do just that. You could also try using sprintf with the appropriate %0.2f (or whatever precision you're looking for). finally (TMTOWTDI), you could use the int keyword to truncate it, which might be more effective. for example, to generate dice rolls:

int( rand 6 ) +1;
Answer: How do I round a number?
contributed by japhy

Different rounding schema:

# 1.1 => 1; 1.9 => 1; -1.1 => -2; -1.9 => -2 $rounded = POSIX::floor($value); # 1.1 => 2; 1.9 => 2; -1.1 => -1; -1.9 => -1 $rounded = POSIX::ceil($value); # 1.1 => 1; 1.9 => 2; -1.1 => -1; -1.9 => -2 $rounded = round($value); sub round { $_[0] > 0 ? int($_[0] + .5) : -int(-$_[0] + .5) }
Answer: How do I round a number?
contributed by powerman

Here shown all round-like functions which exists in perl:

#!/usr/bin/perl use POSIX; @a=(3.3, 3.5, 3.7, -3.3, -3.5, -3.7, 3.45); print "number\tint\tprintf\tfloor\tceil\n"; printf "%.2f\t%.1f\t%.1f\t%.2f\t%.2f\n", $_, int, $_, floor($_), ceil($_) foreach (@a);
This code produce this output:
number	int	printf	floor	ceil
3.30	3.0	3.3	3.00	4.00
3.50	3.0	3.5	3.00	4.00
3.70	3.0	3.7	3.00	4.00
-3.30	-3.0	-3.3	-4.00	-3.00
-3.50	-3.0	-3.5	-4.00	-3.00
-3.70	-3.0	-3.7	-4.00	-3.00
3.45	3.0	3.5	3.00	4.00
Answer: How do I round a number?
contributed by 5mi11er

I was looking for a ceil(x,y) function similar to what exists in excel, where x is the thing to round, and y is "significance" according to Excel v9 (Office 2000), I prefer to think of it as "interval".

But, I was also intrigued by several of the other answers given (found via supersearch), and then in a fit of playing around, I created several variations below.

My personal restrictions were to use math operations, and not rely on other modules. This eliminated the printf and POSIX answers.

use strict; use warnings; ######## # This version takes two arguments # The number to round # And the number of places to the right or left of the decimal poin +t # Positive numbers to the left, negative numbers to the right. # Think powers of 10. # # Parts of this were stolen from nodeid=8781, and nodeid=1873 # most notably from Roy Johnson and wrvhage ######## sub round { my ($number, $places) = @_; my $sign = ($number < 0) ? '-' : ''; my $abs = abs($number); if($places < 0) { $places *= -1; return $sign . substr($abs+("0." . "0" x $places . "5"), 0, $places+length(int($abs))+1); } else { my $p10 = 10**$places; return $sign . int($abs/$p10 + 0.5)*$p10; } } ######## # Simple Ceiling function ######## sub ceil { my ($num) = @_; return int($num) + ($num > int($num)); } ######## # Function modeled after Excel's two argument function # Number to act on # Interval to return (2 would return only multiples of 2, 3 multipl +es of 3 etc) ######## sub ceil_xl { my ($num,$interval) = @_; return ceil($num / $interval) * $interval; } ######## # Function derived from node_id=270920 # Returns next nearest mulitple of 5 up to 50, then nearest 25 up t +o 100, # then nearest quarter of current power of 10. ######## sub ceil_qtrs { my ($num) = @_; my $abs=int(abs($num)); my $interval; # This next line was the originally given answer from Abigail-II, # it was obtuse enough that I needed to break it down to fully unders +tand it, # then I wanted to modify it, and I then left my version in the more +readable # style. # my $frac = $num < 100 ? 5 : (1 . ("0" x (length ($num) - 1))) / + 4; if($abs < 40) { $interval = 5; } elsif($abs < 100) { $interval = 25; } else { $interval = "1".("0"x(length($abs)-1)); $interval = $interval/4; } return ceil($num / $interval) * $interval; } my @data = qw(1 2 3.14159 4.634 5 5.165 6 9 10 10.257 13 23 89 99 100 +101 214 702 1328 -1 -2 -3.14159 -4.634 -5 -5.165 -6 -9 -10 -10.257 -13 -23 -89 -99 - +100 -101 -214 -704 -1328 ); my $format = " "."%13.13s "x8 . "\n"; printf ($format, "number","ceil_qtrs","ceil_xl(x,3)","ceil_xl(x,8)","c +eil(x)","round(x,0)","round(x,1)","round(x,-2)"); foreach (@data) { printf ("%13.13s ",$_); printf ("%13d ",ceil_qtrs($_)); printf ("%13d ",ceil_xl($_,3)); printf ("%13d ",ceil_xl($_,8)); printf ("%13d ",ceil($_)); printf ("%13d ",round($_,0)); printf ("%13d ",round($_,1)); printf ("%13.3f ",round($_,-2)); print "\n"; }
Answer: How do I round a number?
contributed by Mago

If you are using integers, and want to use Math::BigInt:


Math::BigInt - Arbitrary size integer math package

DESCRIPTION

All operators (inlcuding basic math operations) are overloaded if you declare your big integers as

  $i = new Math::BigInt '123_456_789_123_456_789';  

(snip)


METHODS

round

$x->round($A,$P,$round_mode); # round to accuracy or precision using + mode $r

Answer: How do I round a number?
contributed by Nimster

How about

Use integer; $thevalue*=1;
Seems the simplest, IMHO. It rounds everything down, btw - so it acts kinda like 'div' in PASCAL. That's where it's useful. For rounding to the nearest, use any of the above.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (5)
    As of 2014-12-21 21:56 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      Is guessing a good strategy for surviving in the IT business?





      Results (108 votes), past polls