As in Perl to round a number to the nearest integer in a big way

Task. In Perl, the program has a variable which is a number. You need to round it to the nearest whole in a big way.

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

  • 10.001
  • 10.4
  • 10.5
  • 10.99
  • 11

The solution is to use the function ceil

The best way to solve this problem is to use the function ceil 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

use POSIX;

my $number = 10.3;

print ceil($number);

The program will display the number 11.

  • 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 ceil($number); — Used function ceil and display the result of its work.

Function ceil (in English this word is translated as "ceiling") 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 ceil there is still a function of floor ("gender"), which rounds a number to the nearest integer. Ie in the case of non-negative numbers just cuts off the entire fractional part.

In case of negative numbers

Function ceil for negative numbers works the same way as for positive numbers — rounds the number to the nearest integer in a big way.

In the case of negative numbers, it means that the function will simply cut off the entire fractional part.

All of these numbers when using ceil will become the number -5:

  • -5
  • -5.1
  • -5.5
  • -5.9

Related topics

Other articles