How do you round a floating point number in Perl with code example

This tutorial explains multiple ways to round floating numbers in Perl.

Perl Floating number round example

There are multiple ways we can round a float number Floating numbers can be rounded in two types.

  • ceiling: a rounding number to a number greater than the current number. For example round of 2.6 is 3.

  • Floor: rounding number to a number less than the current number. For example round of 2.6 is 2.

  • using Math::round module

Math::round🔗 module provides extension functions for rounding numbers.

  • First import all functions of the Math::round module
  • call the round function with a given floating number
  • Returns the roundest integer number
use Math::Round qw(:all);

my $floatNumber= 123.12
my $result = round( $floatNumber );
print "$result";

Output:

123
  • use POSIX module POSIX module provides rounding utility functions
  • ceil: return the rounded to a number greater than a given number.
  • floor: Return the rounded to a number less than a given number.

Here is an example

use POSIX;
my $floatNumber= 123.12;
my $result = ceil( $floatNumber );
my $result1 = floor( $floatNumber );

print "$result\n";# 124
print "$result1"; #123

Output:

124
123
  • use the Math::BigFloat module

Math::BigFloat🔗 module provides various utility methods for number systems. First, create a number using BigFloat -> new method.

  • Call the bfround function to return the nearest integer
  • call the bfloor function to return the floor of a floating number
  • call the bceil function to return the floor of a floating number

Here is an example

use Math::BigFloat;

my $floatNumber= 123.12;
print Math::BigFloat->new($floatNumber)->bfround(1),"\n";#123
print Math::BigFloat->new($floatNumber)->bfloor(3),"\n"; #123
print Math::BigFloat->new($floatNumber)->bceil(3); #124
  • use the sprintf function

sprintf function converts given floating number with expression and does rounding number

my $floatNumber= 123.12121;
my @result=sprintf "%.0f", $floatNumber;
print "@result" #123

Perl Limit decimal places in floating numbers

This example limits the decimal places in a floating number. The printf function returns the floating number by limiting decimal places.

my $floatNumber= 123.12121;
printf("%.2f\n",123.11111);
printf("%.2f\n",123.666);
printf("%.2f\n",111.61266);

Output:

123.11
123.67
111.61