Perl, floor and ceiling a floating number

rgbcof
rgbcof used Ask the Experts™
on
$floatnum = "1234.5678";
# I want to floor the number to 3rd digit after the decimal.  So 1234.567
# also, ceiling it to:  1234.568
Comment
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";

Author

Commented:
$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.

Author

Commented:
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 :(
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
use POSIX;
$floatnum = "1234.5678";
$floor=floor($floatnum*1000)/1000;
$ceiling=ceil($floatnum*1000)/1000;
#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