如何在 Perl 中将数字格式化为 2 个小数位? [英] How can I format a number to 2 decimal places in Perl?

查看:175
本文介绍了如何在 Perl 中将数字格式化为 2 个小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中将数字格式化为小数点后两位的最佳方法是什么?

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

例如:

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

推荐答案

这取决于你想如何截断它.

It depends on how you want to truncate it.

sprintf 使用 %.2f 格式将执行正常的四舍五入".

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 是一个浮点数(基本上是一个小数),.2 表示只打印两位小数.

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

如果你想截断而不是舍入,那么使用int.由于这只会截断为整数,因此您必须将其乘以并再次除以您想要的十次幂的小数位数.

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

<小时>

对于任何其他舍入方案,请使用 ​​Math::Round.

这篇关于如何在 Perl 中将数字格式化为 2 个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆