Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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

by glickjd (Novice)
on Sep 08, 2002 at 17:39 UTC ( #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)
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 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: 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: 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
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? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2015-07-06 20:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (82 votes), past polls