CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Advanced:
setting a 7 digit number



Sep 22, 2001, 6:32 AM

Post #1 of 3 (1933 views)
setting a 7 digit number Can't Post

ok, i am having a bit of a problem coming up with exactly how to set numbers to always have 7 digits.. for example:

3456 should be: 0003456
10092 should be 0010092
i need it to always have seven digits

i know how to set the length after a decimal:
$number = sprintf( "%.7f", $number);

but i cannot find how to set the length before..

thanks for any help,

I Hope this helps...

perl programmers don't die.. they just start writing a new script.


Sep 22, 2001, 7:02 AM

Post #2 of 3 (1927 views)
Re: setting a 7 digit number [In reply to] Can't Post

If you only deal with integers, that's easy. Just use

sprintf "%07d", $num;

This format string will tell sprintf to reserve 7 digits for $num and fill it up with leading zeroes. So that's more or less what I guess you need from your examples.
If you have to deal with floating point values, you've got to know the number of digits following the decimal point. If you want, say, 7 digits in total, including the decimal point, and 2 digits after the decimal point, and leading zeroes, you'd have to write

sprintf "%07.2f", $num;

So the format is basically:

1. a percent sign '%'
2. an optional plus sign '+' to indicate you want +/- printed for each number
3. an optional minus sign to indicate left alignment
4. an optional zero to indicate you want leading zeroes instead of leading spaces
5. the (optional) number of total digits (characters), including sign / decimal point
6. for [efg] a dot followed by the number of digits after the decimal point
7. a type specifier for the argument (e.g. 'd' for integers, 'f' for floats, 'x' for hex...)

...I just realized that I could have copypasted part of the above directly from the manpage... Wink

So, if you want to read the above rules in a bit more detail, just look at perldoc -f sprintf, or get a good book about C programming. (Kernighan/Ritchie also explain printf() format strings in their book.)
Hope this helps.

-- Marcus



Sep 26, 2001, 3:00 PM

Post #3 of 3 (1911 views)
Re: setting a 7 digit number [In reply to] Can't Post

this is an FAQ.


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives