Wednesday, January 6, 2010

Formatting numbers with PHP function

Formatting numbers with PHP function
Hi coding freak...back with PHP tutorial again and again :D. I make this PHP tutorial inspired by a question from a friend. Suppose you have a number 123456789. And you want to display it in the format 123,456,789 (groups per thousand). Normally the number of such formats are used in display applications related to finance. How do we create one? Well .. in PHP, this is not a problem because there are function number_format () that you can use to set the format of these numbers.


Want to know the details of how its use? Read this article until the end.

Before I give examples how to use it, it's good to you to know the syntax number_format () first. The syntax of this function is as follows:

number_format (n [, x [, y, z]);

With the parameter n is the number that will be formatted (the type is float or real, may also integers), x is the number of decimal digits in the decimal point (for real numbers), y is the string as a decimal separator, and z is the string as a group separator per thousand.

If only the parameter n is used, then the numbers will be formatted with no decimal places and groups of thousands separated by ",".

If only the parameters n and x are used, then the numbers will be formatted with the decimal separator shape "." And the group of thousands separated by ",".

And if the four parameters are used, then the numbers will be formatted with the decimal separator and the y are separated by thousands of string written according to the parameters z.

Here are some examples of the use of different parameters and its appearance.


 <?php

$number = 123456789.12345;

// display 123,456,789
$bil = number_format($number);
echo $bil."<br>";

// display 123,456,789.12
$bil = number_format($number, 2);
echo $bil."<br>";

// display 123.456.789,12
$bil = number_format($number, 2, ",", ".");
echo $bil."<br>";

// display 123#456#789-12
$bil = number_format($number, 2, "-", "#");
echo $bil."<br>";

$bil = number_format($number, 0, ",", ".");
echo "Rp. ".$bil.",-";  // display Rp. 123.456.789,-

?>

Easy right?

You can download this tutorial here

Related Posts by Categories



0 comments:

Post a Comment

Maybe this is what you looking for

 

Subscribe Now

Followers

IT Skill is not enough... Copyright © 2009 Designed by Bie Blogger Template