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

前端 未结 1 1183
失恋的感觉
失恋的感觉 2021-01-03 05:00

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

For example:

10      -> 10.00
10.1    -&         


        
相关标签:
1条回答
  • 2021-01-03 05:14

    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.

    0 讨论(0)
提交回复
热议问题