Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Zero padding numbers (was: Ok, here's an easy one)

by glickjd (Novice)
on Sep 08, 2002 at 17:39 UTC ( [id://196055]=perlquestion: print w/replies, xml ) Need Help??

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

I want to make sure my number is always two digits.

my $num = 5;

What's the easiest way to make $num = 05 instead of 5? Can I do this with sprintf?

Thanks

Jeremy

edited: Mon Sep 9 00:22:18 2002 by jeffa - title change

  • Comment on Zero padding numbers (was: Ok, here's an easy one)

Replies are listed 'Best First'.
Re: Ok, here's an easy one
by Aristotle (Chancellor) on Sep 08, 2002 at 17:44 UTC
    See perldoc -f sprintf and man 3 printf my $num = sprintf "%02d", $some_number;

    Makeshifts last the longest.

Re: Ok, here's an easy one
by blakem (Monsignor) on Sep 08, 2002 at 17:44 UTC
    see sprintf
    $num = 5; $zero_padded = sprintf "%02d", $num; print "$zero_padded\n";

    -Blake

Re: Ok, here's an easy one
by abitkin (Monk) on Sep 08, 2002 at 19:53 UTC
    sprintf is too easy, here's a fun way.

    #!/usr/bin/perl my $num = 5; $num = substr("00",2-length($num)) . $num if length($num)<2; print $num;


    I only mention it, becuase sometimes you want to pad with something other than 0's (for example "." when doing a TOC listing.)
      $num = substr("00".$num,-2);
Re: Ok, here's an easy one
by Zaxo (Archbishop) on Sep 08, 2002 at 17:45 UTC

    Yes, format string "%02d".

    After Compline,
    Zaxo

Re: Ok, here's an easy one
by glickjd (Novice) on Sep 08, 2002 at 17:46 UTC
    I think I found it...

    $num = sprintf("%.2u", $num);

    guess I should have gave myself more time. Sorry to be wasting space for a stupid question.

Re: Zero padding numbers (was: Ok, here's an easy one)
by The_Rev (Acolyte) on Sep 09, 2002 at 13:07 UTC
    Just to say it one more time!

    $num = sprintf("%02d", $num);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://196055]
Approved by Aristotle
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-18 04:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found