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
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".%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.For any other rounding scheme use Math::Round.