在perl中舍入十进制数字,结果错误 [英] Rounding decimal numbers in perl, wrong result

查看:115
本文介绍了在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 . "\n";          # 101
print floor($num) . "\n";   # 100
print int($num) . "\n";     # 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 . "\n";          # 101
print floor($num) . "\n";   # 101
print int($num) . "\n";     # 101

正确的方法是什么?

推荐答案

floor()不用于四舍五入,它会向下舍入到最接近的整数.

floor() is not for rounding, it goes down to the nearest integer.

请参阅此旧帖子:如何进行舍入Perl中的浮点数?

这篇关于在perl中舍入十进制数字,结果错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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