Perl – How to format a number to 2 decimal places in Perl

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

Best Answer

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.

Related Topic