Skip to content

PHP Tutorial Numbers and Math

Number Formatting

Lesson 76 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Raw numbers are hard to read. 1234567.5 is better shown as 1,234,567.50. number_format() does that.

index.php
PHP
<?php
$amount = 1234567.5;

echo number_format($amount) . "\n";
echo number_format($amount, 2);
Output
OUTPUT
1,234,568
1,234,567.50

The four arguments

index.php
PHP
<?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
Output
OUTPUT
1,234,567.89
1.234.567,89
1 234 567.89

Prices

index.php
PHP
<?php
$price = 1999;

echo "Price: " . number_format($price, 2) . " USD";
Output
OUTPUT
Price: 1,999.00 USD

Percentages

index.php
PHP
<?php
$passed = 42;
$total = 56;

echo number_format($passed / $total * 100, 1) . "%";
Output
OUTPUT
75.0%

Keep the maths separate

number_format() returns a string. Never calculate with its result.

index.php
PHP
<?php
$formatted = number_format(1234.5, 2);   // "1,234.50"

var_dump($formatted + 1);
Output
OUTPUT
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.

index.php
PHP
<?php
$formatter = new NumberFormatter("en_IN", NumberFormatter::DECIMAL);

echo $formatter->format(1234567.5);
Output
OUTPUT
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.

index.php
PHP
<?php
$priceInCents = 1999;

echo number_format($priceInCents / 100, 2);
Output
OUTPUT
19.99
lightbulb
Format at the edge
Keep numbers as numbers inside your code, and format them only when you print them in HTML.