Rounding decimal numbers in perl, wrong result

I hate decimal numbers. For 1.005, I do not get the expected result 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 right way to do this?

+3
source share
2 answers

floor() not for rounding, it drops to the nearest integer.

See this old post: How do you combine a floating point number in Perl?

+3
source

"" - , , . , , .

int() - , . - .

; , , " ". : , siginficant 5. 9 , : 1,2,3,4,5,6,7,8,9.

, , , - . , , - , . , 5 . .

% perl -e 'printf "%.0f\n", $_+.5 for -10 .. +10'

-10 -8 -8 -6 -6 -4 -4 -2 -2 -0 0 2 2 4 4 6 6 8 8 10 10

" ":

% perl -e 'print int($_+.5)," " for -10 .. +10; print "\n"'

:

 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 0 1 2 3 4 5 6 7 8 9 10 

--:

% perl -le 'printf "%.1f ", $_+.05 for -10 .. +10'

-9.9 -8.9 -8.0 -7.0 -6.0 -5.0 -4.0 -3.0 -1.9 -0.9 0.1 1.1 2.0 3.0 4.0 5.0 6.0 7.0 8.1 9.1 10.1 

, :

% perl -le 'printf "%.2f ", $_+.05 for -10 .. +10'

-9.95 -8.95 -7.95 -6.95 -5.95 -4.95 -3.95 -2.95 -1.95 -0.95 0.05 1.05 2.05 3.05 4.05 5.05 6.05 7.05 8.05 9.05 10.05 

, .

+2

Source: https://habr.com/ru/post/1778838/


All Articles