Вопрос по perl – Функция Perl int и заполнение нулями

2
  1. I have the below Perl function to display up to two decimals places. It's not working when the input value is 2.01, and it gives the output as 2 instead of 2.01. I am not sure why it's rounding.

Error: User Rate Limit Exceeded

    my $ramount = 2.01;
    $ramount = int($ramount*100)/100;
    printf "output1: $ramount";
  1. If I have values like .2, .23, .2345, 1,23, 23.1, and 9, what function can I use to pad zeros so that it displays 0.2, 0.23, 0.2345, 1, 23, 23.1, and 9?

Ваш Ответ

2   ответа
1

perldoc perlfaq4:

Why is int() broken?

Your int() is most probably working just fine. It's the numbers that aren't quite what you think. First, see the answer to "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?".

For example, this

print int(0.6/0.2-2), "\n";

will in most computers print 0, not 1, because even such simple numbers as 0.6 and 0.2 cannot be presented exactly by floating-point numbers. What you think in the above as 'three' is really more like 2.9999999999999995559.

Error: User Rate Limit Exceeded
6

  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>

printf "%04d", $number

printfsprintf

Похожие вопросы