Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hi i would like to print my numbers with the same format with 2 decimal point exp.

80.00
45.34
56.43
45.00

Replies are listed 'Best First'.
Re: decimal point
by ehdonhon (Curate) on Feb 12, 2002 at 19:04 UTC

    You want to take a look at printf. I believe the specific format you are looking for is "%0.2f"


    UPDATE:I accidentally said 0.2d, I meant 0.2f but already clicked on submit. Thought I could fix it before anybody saw it, but ovid was too fast for me. :)

      Close. %0.2f.

      perl -e '$x=80.03723;printf "%0.2f", $x'

      Cheers,
      Ovid

      Update: For those who may be confused, ehdonhon originally had "%0.2d", instead of "%0.2f". My reply looks a bit odd without that context.

      Update 2: It seems I made my original post before ehdonhon fixed /h(is|er)/ node. Then, I made made my update before seeing ehdonhon's update, thus, my update looks confusing in light of the other update. Sigh. I guess we'll play ping-pong with the updates :)

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: decimal point
by rob_au (Abbot) on Feb 13, 2002 at 00:18 UTC
    In addition to the direct answers to your question above from ehdonhon and Ovid, I would just like to add a link through to the excellent tutorial on the printf function by reptile here - Its an excellent overview of the function and how to use it and should answer any further questions or concerns that you have with this function.

     

    perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

Re: decimal point
by Bishma (Beadle) on Feb 13, 2002 at 04:59 UTC
    If you want to do anything with the numbers besides print them right to the screen, you can use sprintf like so:
    $two_decimal_number = sprintf "%0.2f", $x;
    then the variable $two_decimal_number will contain the number in the format you're looking for. You can then print it or manipulate it or whatever.