Perl program that rounds up the amount after the decimal point

Let's create a Perl program that rounds up the amount after the decimal point. It can be used for rounding when dividing the amount.

For example, let's assume that the total amount of money borne by the buyer / seller is 9800 yen and the buyer's burden is "33/365". It is not divisible when divided.

In such a case, you can select either rounding down or rounding up after the decimal point, but this time let's consider the case of rounding up.

Round up the amount after the decimal point

To round up the amount after the decimal point, add 1 after using the int function.

use strict;
use warnings;

# Amount (886.027397260274)
my $price = 9800 * (33/365);

# Round up the amount after the decimal point (887)
my $price_cut = int($price) + 1;

# Output result
print "$price_cut\n";

You can copy and paste this program and try it immediately at PerlBanjo.

How to round up even if the price is negative?

You may be using a negative price, which means a loss. In such a case, if you run the above program, it will be devaluated. "-886.027397260274" becomes "-885".

This shouldn't be what you want. Below is a program that works correctly even if the price is negative.

Using the ternary operator, if the price is larger than 0, the above processing is performed, and if the price is smaller than 0, "-1" is performed.

use strict;
use warnings;

# Amount (886.027397260274)
my $price = -9800 * (33/365);

# Round up the amount after the decimal point (-887)
my $price_cut = $price > 0 ? int($price) + 1 : int($price) - 1;

# Output result
print "$price_cut\n";

You can copy and paste this program and try it immediately at PerlBanjo.

Associated Information