'How can I format a number to 2 decimal places in Perl?

What is best way to format a number to 2 decimal places in Perl?

For example:

10      -> 10.00
10.1    -> 10.10
10.11   -> 10.11
10.111  -> 10.11
10.1111 -> 10.11


Solution 1:[1]

It depends on how you want to truncate it.

sprintf with the %.2f format will do the normal "round to half even".

sprintf("%.2f", 1.555);  # 1.56
sprintf("%.2f", 1.554);  # 1.55

%f is a floating point number (basically a decimal) and .2 says to only print two decimal places.


If you want to truncate, not round, then use int. Since that will only truncate to an integer, you have to multiply it and divide it again by the number of decimal places you want to the power of ten.

my $places = 2;
my $factor = 10**$places;
int(1.555 * $factor) / $factor;  # 1.55

For any other rounding scheme use Math::Round.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Schwern