Raw numbers are hard to read. 1234567.5 is better shown as 1,234,567.50. number_format() does that.
<?php
$amount = 1234567.5;
echo number_format($amount) . "\n";
echo number_format($amount, 2);
1,234,568
1,234,567.50
The four arguments
<?php
// number_format(number, decimals, decimal_separator, thousands_separator)
echo number_format(1234567.891, 2, ".", ",") . "\n"; // US style
echo number_format(1234567.891, 2, ",", ".") . "\n"; // European style
echo number_format(1234567.891, 2, ".", " "); // spaces
1,234,567.89
1.234.567,89
1 234 567.89
Prices
<?php
$price = 1999;
echo "Price: " . number_format($price, 2) . " USD";
Price: 1,999.00 USD
Percentages
<?php
$passed = 42;
$total = 56;
echo number_format($passed / $total * 100, 1) . "%";
75.0%
Keep the maths separate
number_format() returns a string. Never calculate with its result.
<?php
$formatted = number_format(1234.5, 2); // "1,234.50"
var_dump($formatted + 1);
Warning: A non-numeric value encountered in /path/to/index.php on line 4
int(2)
Do the maths with the original number. Format only at the last step.
Indian digit grouping and other locales
The intl extension has a NumberFormatter class that follows a locale’s rules, including Indian digit grouping and currency symbols.
<?php
$formatter = new NumberFormatter("en_IN", NumberFormatter::DECIMAL);
echo $formatter->format(1234567.5);
12,34,567.5
intl is not enabled on every host. Check with extension_loaded("intl").
Money as integers
For prices, store the smallest unit as an integer (cents or paise), then format when displaying.
<?php
$priceInCents = 1999;
echo number_format($priceInCents / 100, 2);
19.99