April 24, 2006

Use PHP number_format

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 6:17 pm

Ok, here is a basic one, I thought I would provide a quick overview of how the PHP number_format function works for presentation of numbers.

Invocation

string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

When you would like to represent a number to the user you can make use of the number_format PHP function. It accepts a number and a series of optional method parameters. Your optional parameters specify how you wish to present your number. You can either specify 1, 2 or 4 parameters (therfore not 3).
Examples

To display a 2 decimal place number (such as a currency) you can use:

// To display myValue (4.3123123123) as 4.31
print(number_format($myValue, 2));

To display a number with thousands represented by a ‘,’ and the decimal represented by a ‘.’ you can use:

// To display myValue (4500.131313) as 4,500.13
print(number_format($myValue, 2, '.', ','));

For those of you who use Smarty for presentation, you can invoke a simple decimal presentation via:

{$myValue|@number_format:2}

Using smarty you can pipe your input into various PHP methods. The above example demonstrates how the parameter $myValue gets piped as the first parameter to the number_format function, followed by the second parameter ‘2′. The above call is the same as our first example: number_format($myValue, 2);

Further Manipulations

If you are looking for rounding a number for use in an equation, you will want to have a look at the PHP round() function located here. An example would be:

<p align="left">// Makes a 4.326 become 4.33 in value.
$myRoundedVal = round($myVal,2);</p>

If you are looking for a quick way to pad with zeros (zerofill), use the (powerful) PHP sprintf() function. An example would be:

// Make a digit zero padded, such as 70 = '070' or 7 = '007'
print(sprintf("%03d", $myVal)); // Change %03d with %04d etc for more padded zeros
Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  • YahooMyWeb

2 Comments

  1. Should also be noted that number_format() returns a string, so perform all numerical calculations before using number_format().

    Also, another alternative to sprintf() for zerofilling is the str_pad() function:

    echo str_pad(6, 3, “0″, STR_PAD_LEFT);

    Comment by Richard Lee — April 26, 2006 @ 9:39 am

  2. Creating an RGB Value using sprintf() would be sprintf(’#%02X%02X%02X’, $red, $green, $blue);

    Comment by Cameron Manderson — April 28, 2006 @ 9:16 am

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.