TechTricks
Technical answers from the trenches 
 
 
 
 

     
   
Perl: Printing Leading Zeros with Numeric Scalars
 
   
by Lance Leonard 
 Posted: 01 July 2000
 
   
 
 Applies to: perl 5.x
 
       
   

Question: I have a numeric scalar that I want to print using leading zeros. How do I do this?

Answer: Use printf, sprint, or sprintf to convert the value to a string, as shown in the following code fragment:

   my( $num ) = 3.1415927;
   my( $out ) = sprintf( "%06d", $num);
   print "$out"; # prints "000003"

   printf "%06.2f\n", $num;  # prints "003.14"

Keep the following points in mind:

1. The leading zeros are indicated by the zero (0) following the percent symbol (%) of the format specifier.

2. The actual conversion is controlled by the final character in the format specifier. In the above examples, d converts values to strings representing signed decimal integers and f yields strings representing signed floating-point values. Both specifiers round the value.

3. Rounding precision is controlled by the integer following the decimal point (.).

This actually is documented in a variety of sources, but not terribly clearly. Most sources appear to presume that you're already familiar with these functions and the layout of the format specifiers. For complete details, see the man page for printf(3). (If you're not familiar with man pages, this article provides a brief overview.)

 

       

Top

Feedback About Paradox Delphi Assorted Web Stuff
 
 
Copyright © 2000-2004, techtricks.com; All Rights Reserved.
Acknowledgements, Disclaimers, Terms and Conditions.
Article last updated on 31 May 2003

 

Other Sites: Paradox, Delphi, Perl, Web Stuff, and More


 

[- End -]