Does perl have a round function? What about ceil() and floor()?
2010-01-23 00:51
363 查看
Does perl have a round function? What about ceil() and floor()?
Perl does not have an explicit round function. However, it is verysimple to create a rounding function. Since the int() function simply
removes the decimal value and returns the integer portion of a number,
you can use
sub round {
my($number) = shift;
return int($number + .5);
}
If you examine what this function is doing, you will see that any
number greater than .5 will be increased to the next highest integer,
and any number less than .5 will remain the current integer, which has
the same effect as rounding.
A slightly better solution, one which handles negative numbers as well,
might be to change the return (above) to:
return int($number + .5 * ($number <=> 0));
which will modify the .5 to be either positive or negative, based on
the number passed into it.
If you wish to round to a specific significant digit, you can use the
printf function (or sprintf, depending upon the situation), which does
proper rounding automatically. See the perlfunc man page for more
information on the (s)printf function.
Version 5 includes a POSIX module which defines the standard C math
library functions, including floor() and ceil(). floor($num) returns
the largest integer not greater than $num, while ceil($num) returns the
smallest integer not less than $num. For example:
#!/usr/local/bin/perl
use POSIX qw(ceil floor);
$num = 42.4; # The Answer to the Great Question (on a Pentium)!
print "Floor returns: ", floor($num), "/n";
print "Ceil returns: ", ceil($num), "/n";
Which prints:
Floor returns: 42
Ceil returns: 43
相关文章推荐
- What kinds of iterators of C++'s copy function requires? What about reverse or unique?
- What Effects Does 'Replicate Seed Data' Concurrent Request Have On Appls?
- what does “static int function(…) __acquires(..) __releases(…){” mean?
- what does perl language play in hardware design?
- What does the PF function do in Primefaces
- What You Have to Know about ASP.net MVC
- What does "Error: L6248E: cannot have address type relocation" mean?
- Think more about what you have
- Why compilers have failed and what we can do about it
- Device 'xilinx-keypad' does not have a release() function, it is broken and must be fixed.
- Mongoose - What does the exec function do?
- Think More About What You Have
- What does the SQLERRM Function do
- cannot add a child that doesnot have a YogoNode to a parent without a measure function!
- What does this bit-manipulating function do?
- What does the SQLCODE Function do
- What does _imp_<Function> mean?
- Learning Perl: 1.2. What Does "Perl" Stand For?
- php取整函数ceil,floor,round,intval函数的区别
- Java Math的 floor,round和ceil的总结