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.

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. 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 Answers 2

6

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>

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...

As to padding, try

printf "%04d", $number

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

Sign up to request clarification or add additional context in comments.

Comments

1

From 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.

1 Comment

Also, it must be noted, that int() is a truncation operation, rather than a rounding operation. I = int(f +0.5) is the explicit rounding solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.