Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 726
Devesh Agrawal Avatar asked Jan 27 '16 17:01

Devesh Agrawal


1 Answers

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.

like image 127
Schwern Avatar answered Oct 05 '22 23:10

Schwern