Perl int函数和填充零 [英] Perl int function and padding zeros

查看:111
本文介绍了Perl int函数和填充零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我有下面的Perl函数来显示最多两位小数.当输入值为2.01时,它不起作用,并且输出为2而不是2.01.我不确定为什么要四舍五入.

我将输出而不是printf写入了文件,但仍然将output1设为2.

Instead of printf I wrote the output to a file, but still it gives me output1 as 2.

    my $ramount = 2.01;
    $ramount = int($ramount*100)/100;
    printf "output1: $ramount";

  1. 如果我具有.2,.23,.2345、1,23、23.1和9之类的值,我可以使用什么函数填充零,以使其显示0.2、0.23、0.2345、1、23、23.1,和9?

推荐答案

我认为此顺序将回答您的问题:

I think this sequence will answer your question:

  DB<1> $a=2.01

  DB<2> p $a
2.01
  DB<3> printf "%20.10f\n", $a
        2.0100000000

  DB<4> printf "%20.16f\n", $a
  2.0099999999999998

  DB<5> printf "%20.16f\n", ($a*100)
200.9999999999999716

  DB<6> printf "%20.16f\n", ($a*100)/100
  2.0099999999999998

  DB<7> printf "%20.16f\n", int($a*100)
200.0000000000000000

  DB<8> printf "%20.16f\n", int($a*100)/100
  2.0000000000000000

  DB<9>

从本质上讲(这在SO上已经回答了很多次),不能完全将2.01表示为浮点数.如上所示,最接近的浮点数是2.009999999999999716 ...

Essentially (and this has been answered many times on SO), 2.01 cannot be represented EXACTLY as a floating point number. The closest possible float is, as you see above, 2.009999999999999716...

关于填充,请尝试

printf "%04d", $number

格式中的前导零将printf(或sprintf)告诉左键盘为零.

The leading zero in the format tells printf (or sprintf) to left-pad with zero.

这篇关于Perl int函数和填充零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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