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

number formatting

by costas (Scribe)
on Aug 08, 2001 at 18:53 UTC ( #103069=perlquestion: print w/replies, xml ) Need Help??

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

I want to format integers so that they are always of a certain length (10 chars)

ie. 15 would become 0000000015
4564747 -> 0004564747
7899 -> 0000007899 etc...

i want to basically add zeros to the front of an integer to make them always the same length

cos

Replies are listed 'Best First'.
Re: number formatting
by nardo (Friar) on Aug 08, 2001 at 18:57 UTC
    Using %010d in printf or sprintf will 0 pad them to a length of 10 (the leading 0 will pad them with zeroes and the remainder of the number is the length).
Re: number formatting
by VSarkiss (Monsignor) on Aug 08, 2001 at 18:58 UTC

    printf and sprintf are your friends. Try: printf "%010d", 15;

    HTH

Re: number formatting
by aquacade (Scribe) on Aug 08, 2001 at 19:10 UTC
    Lifted From perlfaq4 - Data Manipulation

    How do I pad a string with blanks or pad a number with zeroes? (This answer contributed by Uri Guttman, with kibitzing from Bart Lateur.)

    In the following examples, $pad_len is the length to which you wish to pad the string, $text or $num contains the string to be padded, and $pad_char contains the padding character. You can use a single character string constant instead of the $pad_char variable if you know what it is in advance. And in the same way you can use an integer in place of $pad_len if you know the pad length in advance.

    The simplest method uses the sprintf function. It can pad on the left or right with blanks and on the left with zeroes and it will not truncate the result. The pack function can only pad strings on the right with blanks and it will truncate the result to a maximum length of $pad_len.
    Left padding a string with blanks (no truncation: $padded = sprintf("%${pad_len}s", $text); # Right padding a string with blanks (no truncation): $padded = sprintf("%-${pad_len}s", $text); # Left padding a number with 0 (no truncation): $padded = sprintf("%0${pad_len}d", $num); # Right padding a string with blanks using pack (will truncate): $padded = pack("A$pad_len",$text);
    If you need to pad with a character other than blank or zero you can use one of the following methods. They all generate a pad string with the x operator and combine that with $text. These methods do not truncate $text.

    Left and right padding with any character, creating a new string:
    $padded = $pad_char x ( $pad_len - length( $text ) ).$text; $padded = $text . $pad_char x ($pad_len - length($text));
    Left and right padding with any character, modifying $text directly:
    substr($text, 0, 0)=$pad_charx($pad_len-length($text)); $text .= $pad_char x ($pad_len - length($text));
    Update: Check out the Schwartzian Transform if you need to sort these numbers later!

    ..:::::: aquacade ::::::..

      Don't you need to do a scalar($variable) to make sure it's returned as a string instead of a number?

      Sorry, no perl available for testing (the horror!)
Re: number formatting
by Hofmator (Curate) on Aug 08, 2001 at 19:08 UTC

    and apart from the perldoc to printf and sprintf this excellent tutorial Using (s)printf() here on PM might help you with the myriad of options for the format string - if you need to print something more complicated then a zero padded number ;)

    -- Hofmator

Re: number formatting
by gryphon (Abbot) on Aug 08, 2001 at 19:14 UTC

    The best way is probably:

    my $number = 15; my $size = 10; printf "%0" . $size . "d", $number;

    Alternative:

    my $number = 15; my $size = 10; print '0' x ($size - length($number)) . $number;

    -gryphon
    code('Perl') || die;

Re: number formatting
by costas (Scribe) on Aug 08, 2001 at 19:28 UTC
    im doing this:

    $result = sprintf('%015d', $integer)

    which when printed to html is:

    $result = sprintf('%015d', 9789673814172)

    the answer i get however is 000001443791101 instead of 009789673814172. anyone know what wrong?

      I would guess that you rolled your 32 bit int over many times. Playing around in bc I got 1443346588 by subtracting out powers of 2 to get lower than 2^32

      On a 32 bit box with 32 bit perl I get -00000000000001. If you have the perl with the really long ints you might try %015ld which should allow a longer int.

      On an Alpha box (64 bits native) the %015ld works as expected (009789673814172). Also you may try (with loss of precision for non simple assignments %015.0lf which works as one might expect on my 32 bit perl.

      try result = sprintf('%015.f', 9789673814172);

      -- Hofmator

Re: number formatting
by costas (Scribe) on Aug 08, 2001 at 19:35 UTC
    it seems i cant pad a number which is over 9 integers long. anyone know the cure?
      The problem is your number is way too big. Treat it as a string, and all will be fine:
      printf "%015s", "3843850840892";

      _____________________________________________________
      Jeff japhy Pinyan: Perl, regex, and perl hacker.
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: number formatting
by trantor (Chaplain) on Aug 09, 2001 at 10:04 UTC

    When it comes to number formatting, the snippet in this node can be useful

    -- TMTOWTDI

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2022-06-27 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My most frequent journeys are powered by:









    Results (88 votes). Check out past polls.

    Notices?