phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Padding Numbers with Zeroes

Tag: number, padding   Category: PHP Basic
post: 16 Mar 2008 read: 56


PHP Number Tips - Part 7: If you want to format a number with leading or trailing zeroes, you can use the printf( ) or sprintf( ) function with appropriate format specifiers such as:

<?php
//result: 00012
printf("%05d", 12);

//result: 00169.000
printf("%09.3f", 169);

//result: 00003475.986000
printf("%015.6f", 3475.986);

//result: 74390.99
printf("%02.2f", 74390.98647);
?>

PHP's printf( ) and sprintf( ) functions are very similar to the printf( ) and sprintf( ) functions. Both functions accept two arguments, a series of format specifiers and the raw string or number to be formatted. The input is then formatted according to the format specifiers and the output is either displayed with printf( ) or assigned to a variable with sprintf( ).
Beneath are some of the common field templates:


<table>
  <tr>
    <td><b>Specifier</b></td>
	<td><b>What It Means</b></td>
  </tr>
  <tr>
    <td>%s</td>
	<td>String</td>
  </tr>
  <tr>
    <td>%d</td>
	<td>Decimal number</td>
  </tr>
  <tr>
    <td>%x</td>
	<td>Hexadecimal number</td>
  </tr>
  <tr>
    <td>%o</td>
	<td>Octal number</td>
  </tr>
  <tr>
    <td>%f</td>
	<td>Float number</td>
  </tr>
</table>

You can also combine these field templates with numbers that indicate the number of digits to display for example: %1.2f. It implies that only two digits should be displayed after the decimal point and adding 0 as the padding specifier that tells about the function to zero-pad the numbers to the specified length. Beside that, you can use an alternative padding character by prefixing it with a single quote ( ' ).




| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting