在perl中舍入十进制数,错误的结果 [英] Rounding decimal numbers in perl, wrong result
本文介绍了在perl中舍入十进制数,错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我讨厌十进制数字.对于 1.005,我没有得到以下代码所期望的结果.
I hate decimal numbers. For 1.005 I don't get the result I expect with the following code.
#!/usr/bin/perl -w
use strict;
use POSIX qw(floor);
my $num = (1.005 * 100) + 0.5;
print $num . "
"; # 101
print floor($num) . "
"; # 100
print int($num) . "
"; # 100
对于 2.005 和 3.005,它工作正常.
For 2.005 and 3.005 it works fine.
通过这个丑陋的hack",我得到了预期的结果.
With this ugly "hack" I get the expected result.
#!/usr/bin/perl -w
use strict;
use POSIX qw(floor);
my $num = (1.005 * 100) + 0.5;
$num = "$num";
print $num . "
"; # 101
print floor($num) . "
"; # 101
print int($num) . "
"; # 101
这样做的正确方法是什么?
What is the correct way to do this?
推荐答案
floor()
不是四舍五入,而是向下取最接近的整数.
floor()
is not for rounding, it goes down to the nearest integer.
查看这篇旧帖子:你如何舍入Perl 中的浮点数?
这篇关于在perl中舍入十进制数,错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文