Perl, floor and ceiling a floating number

rgbcof used Ask the Experts™
$floatnum = "1234.5678";
# I want to floor the number to 3rd digit after the decimal.  So 1234.567
# also, ceiling it to:  1234.568
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You can try:

 $floatnum = "1234.5678";
 @n = split(/\./,$floatnum);

 $floor = substr($n[1],0,3);
 $floor = "$n[0].$floor";
 $ceiling = sprintf "%.3f" ,$floatnum;

 print  "$floor $ceiling\n";
Another way:

my $floatnum   = 1234.5678;
my $ceil = sprintf("%.3f", $floatnum);
my ($floor) = $floatnum =~ /(\d*\.\d+)\d/;
print $ceil, "\n";
print $floor, "\n";


$floatnum = "1234.5672";

# the ceiling doesn't work if the last digit is less than 5.
# ceiling should be 1234.568
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.


Doesn't take care of all case.   I will post a different question.
Too bad I had a solution for you but got busy and you closed it :(
Most Valuable Expert 2014
Top Expert 2015

use POSIX;
$floatnum = "1234.5678";
#note that neither 1234.567 nor 1234.568 can be represented exactly in IEEE floating point

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial