I hate decimal numbers. For 1.005 I don’t get the result I expect with the following code.
#!/usr/bin/perl -w
use strict;
use POSIX qw(floor);
my $num = (1.005 * 100) + 0.5;
print $num . "\n"; # 101
print floor($num) . "\n"; # 100
print int($num) . "\n"; # 100
For 2.005 and 3.005 it works fine.
With this ugly “hack” I get the expected result.
#!/usr/bin/perl -w
use strict;
use POSIX qw(floor);
my $num = (1.005 * 100) + 0.5;
$num = "$num";
print $num . "\n"; # 101
print floor($num) . "\n"; # 101
print int($num) . "\n"; # 101
What is the correct way to do this?
floor()is not for rounding, it goes down to the nearest integer.See this old post: How do you round a floating point number in Perl?