PHP Formatted Number Output

The Background

This is to demonstrate the use of printf() to format the display of a number using PHP. It was inspired by a question on comp.lang.php where the poster wanted to know how to display a single-digit number as a 2-digit number with a leading zero

The Numbers

num1: 5

num2: 50

num3: 500

The Output

num1 with 2 digits (leading zero): 05

num2 with 2 digits (leading zero): 50

num3 with 2 digits (leading zero): 500

The Code

printf("<p>num with 2 digits (leading zero): %02d</p>", $num);

the %02d part of the string identifies an integer number to be output, to be displayed as 2 digits, with leading zeros if needed. The $num after the string is the variable that holds the number to be displayed. If the number is more than 2 digits, the whole number will be displayed, and is not truncated. For more information on printf() visit the PHP Manual page for printf().


Nigenet Home | Email [email protected]