PHP: How To Format Numbers

In PHP there is an easy way to format numbers with decimal separators and thousands separators an so on. A number like 123456.789 can be easily formated to something like 123,456.79 or 123.456,79. In this article I’ll show you how.

First of all, why do we need to format numbers? Well it’s obvious, that you can read a number like 123,45 very easily. But how about 9348394309.238? 😉 In this case, it will be very useful to add some thousands separators. Because then it will look like this: 9,348,394,309.238. And maybe we want to limit the decimals to two. So it will look like this: 9,348,394,309.24 (please note the rounded decimal). So this makes it way more readable.

But there is another fact, that we should regard. Internationalization! Numbers are formated in different ways around the world. Some use a comma as a thousands separator, some use a dot. The same for the decimal separator. So a formatting function allows you to display your data e.g. in a user defined or in a region specific format.

So, here is the function: number_format()

<?php
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," );
?>

This function needs some arguments:

number:
the number to format
decimals:
how much decimals to display (tho function rounds automatically)
dec_point:
a string with the decimal separator
thousands_sep:
a string with the thousands separator

To work, this function only needs the number. But this would only produce a number without decimals.

Here are some examples:

<?php
// Outputs 123,457
echo number_format (123456.789);
// Outputs 123,456.79
echo number_format (123456.789 , 2 , "." , "," );
// Outputs 123.456,789
echo number_format (123456.789 , 3 , "," , "." );
// Also outputs 123,457
echo number_format (123456.789 , 0 , "." , "," );
?>

You can find more information about this function at php.net/manual/en/function.number-format.php.

(Visited 1,915 times, 1 visits today)

Leave a Comment