When displaying a number in a Web page, it’s nice to format the number in an easy-to-read way. For example, 123,456.78
is nicer to read than 123456.784321
.
PHP’s number_format()
function gives you an easy way to format numbers for displaying to the user. You can separate thousands with commas or other separators, choose the decimal point character, and choose the number of decimal places to display (or display no decimals at all).
Basic number formatting
In its most basic form, number_format()
accepts a number to format, and returns a string containing the formatted number, rounded to the nearest whole number, with commas between each group of thousands:
$myNumber = 1234567.89;
// Displays "1,234,568"
echo number_format( $myNumber );
Specifying the number of decimal places
To add decimal places to the formatted number, specify the number of decimals to add as the second argument. number_format()
rounds the number up or down to the specified number of decimals:
$myNumber = 123456.784321;
// Displays "123,456.78"
echo number_format( $myNumber, 2 );
// Displays "123,456.8"
echo number_format( $myNumber, 1 );
Using different separators
By default, number_format()
uses a dot for the decimal point, and a comma for the thousands separator. To use different separators, pass the new decimal point separator as the third argument, and the new thousands separator as the fourth argument.
The following example displays a number using the French convention — a comma for the decimal point, and a space for the thousands separator:
$myNumber = 123456.784321;
// Displays "123 456,78"
echo number_format( $myNumber, 2, ',', ' ' );
If you wanted to display a number in English notation rounded to 2 decimal places, but without thousands separators, you could write the following:
$myNumber = 123456.784321;
// Displays "123456.78"
echo number_format( $myNumber, 2, '.', '' );
Summary
number_format()
gives you a simple way to display numbers in a nice, easy-to-read format. You’ve learned how to call number_format()
, how to specify the number of decimals to display, and how to display numbers using a different thousands separator and decimal point.
Incidentally, if you need to display a number using words — for example, “one thousand two hundred and thirty-four” — check out the Numbers_Words
PEAR module.
Happy coding!
Leave a Reply