你如何在 Perl 中对浮点数进行四舍五入? [英] How do you round a floating point number in Perl?

查看:23
本文介绍了你如何在 Perl 中对浮点数进行四舍五入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将十进制数(浮点数)四舍五入到最接近的整数?

How can I round a decimal number (floating point) to the nearest integer?

例如

1.2 = 1
1.7 = 2

推荐答案

perldoc -q round

请记住,int() 只是向 0 截断.要舍入到特定位数,sprintf()printf() 通常是最简单的路线.

Does Perl have a round() function? What about ceil() and floor()? Trig functions?

Remember that int() merely truncates toward 0. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route.

    printf("%.3f", 3.1415926535);       # prints 3.142

POSIX 模块(标准 Perl 发行版的一部分)实现ceil()floor() 以及许多其他数学和三角函数职能.

The POSIX module (part of the standard Perl distribution) implements ceil(), floor(), and a number of other mathematical and trigonometric functions.

    use POSIX;
    $ceil   = ceil(3.5);                        # 4
    $floor  = floor(3.5);                       # 3

在 5.000 到 5.003 perls 中,三角函数是在 Math::Complex模块.在 5.004 中,Math::Trig 模块(属于标准 Perl分布)实现三角函数.在内部它使用 Math::Complex 模块,一些函数可能会中断从实轴进入复平面,例如 2 的反正弦.

金融应用程序中的四舍五入可能会产生严重影响,并且应精确指定使用的舍入方法.在这些在这种情况下,不信任正在进行的任何系统舍入可能是值得的Perl 使用,而是实现您需要的舍入函数你自己.

要了解原因,请注意您仍然会在中途遇到问题交替:

In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex module. With 5.004, the Math::Trig module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses the Math::Complex module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2.

Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

To see why, notice how you'll still have an issue on half-way-point alternation:

    for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}

    0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
    0.8 0.8 0.9 0.9 1.0 1.0

不要责怪 Perl.这和 C 中的一样.IEEE 说我们必须做这.Perl 数字,其绝对值是 2**31 下的整数(在32 位机器)将非常像数学整数一样工作.不保证其他数字.

Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.

这篇关于你如何在 Perl 中对浮点数进行四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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