PERL - rounding fractional number

It seems that perl sprintf uses the round-to-even method:

foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
    printf "$i -> %.0f\n", $i;
}
__END__

0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
4.5 -> 4

Where we probably wants to use round-half-up, i.e. output should be as below:

0.5 -> 1
1.5 -> 2
2.5 -> 3
3.5 -> 4
4.5 -> 5

Any suggestion to correct the above code to accomplish the above required result?

use the POSIX module and you'll have access to the ceil() and floor() functions.

Hi Pludi,

Thanks a lot for your torch light and solution.

Cheers ~~ / Mysore 101 Ganapati.

The mathematical method is to add 0.5 and then ignore the decimal place.

Another question arises here:

If I use floor(), as:

#!/usr/bin/perl
use POSIX;
foreach my $i ( 0.4, 0.5, 1.2, 1.6, 2.1, 2.9) {
    printf "$i -> %.0f\n", floor($i);
}
__END__

resulting output as:

0.4 -> 0
0.5 -> 0
1.2 -> 1
1.6 -> 1
2.1 -> 2
2.9 -> 2

If I use ceil(), as:

#!/usr/bin/perl
use POSIX;
foreach my $i ( 0.4, 0.5, 1.2, 1.6, 2.1, 2.9) {
    printf "$i -> %.0f\n", ceil($i);
}
__END__

resulting:

0.4 -> 1
0.5 -> 1
1.2 -> 2
1.6 -> 2
2.1 -> 3
2.9 -> 3

How to roundup the values like,

if ($any_number >= 0.5) then {
    roundup to its higher number
} else {
    roundup to its lower number
)

i.e,

result should be as below:

0.4 -> 0
0.5 -> 1
1.2 -> 1
1.6 -> 2
2.1 -> 2
2.9 -> 3

Is there any dedicated built-in function in PERL, to accomplish this? :confused:

Short answer: no.

Long answer: See perlfaq4

Install the Perl Math::Round module and use the round() function.

#!/usr/bin/perl

use Math::Round;

foreach my $i ( 0.4, 0.5, 1.2, 1.6, 2.1, 2.9) {
    printf "$i -> %.0f\n", round($i);
}

This is the output

0.4 -> 0
0.5 -> 1
1.2 -> 1
1.6 -> 2
2.1 -> 2
2.9 -> 3  

Thanks for your valuable suggestion "fpmurphy" :slight_smile:

I've got it from internet and installed Round.pm module under 'lib\perl5\5.10\Math' and its working now :slight_smile: Thanks.