As in Perl to round a number to the nearest integer

Task. In Perl, the program has a variable which is a number. You need to round it to the nearest whole in the smaller side. I.e. in the case of non-negative numbers this means you just need to cut off the entire fractional part.

Here are some examples of values. All these numbers must be converted to number 10:

  • 10
  • 10.001
  • 10.4
  • 10.5
  • 10.99

The solution is to use the function floor

The best way to solve this problem is to use the function floor from the library POSIX.

Library POSIX comes with Perl, so if you have Perl, this library is available to additionally install nothing.

Here is a sample program:

▶ Run
#!/usr/bin/perl

use POSIX;

my $number = 10.3;

print floor($number);

The program will display the number 10.

  • use POSIX; — connected the library POSIX. As soon as we connected this library, we immediately became available a few functions that are defined in this library.
  • my $number = 10.3; — create a variable $number and put the number 10.3.
  • print floor($number); — Used function floor and display the result of its work.

Function floor (in English this word is translated as "sex") is fairly standard. In many programming languages there is a function with the same name and which works exactly the same.

In addition to the functions floor there is still a function of ceil ("ceiling"), which rounds a number to the nearest integer in a big way.

In case of negative numbers

Function floor for negative numbers works the same way as for positive numbers — rounds the number to the nearest integer.

All of these numbers when using floor will become the number -6:

  • -5.1
  • -5.5
  • -5.9
  • -6

Related topics

Other articles

Comments