number_format() returns a formatted string. Use it for presentation, not as the stored numeric value used in later calculations.
$amount = 1234567.5;
echo number_format($amount, 2); // 1,234,567.50
number_format() returns a string for display. Keep the original numeric value for calculations and format it only when presenting the result.
<?Php
$number=2512589.66785;
echo "Number = $number ";
echo "<br>With formatting = ".number_format($number); // 2,512,590
// Three decimal place
echo "<br>With formatting = ".number_format($number,3); // 2,512,589.668
// Three decimal place, '.' as decimal separator and # as thousand separator
echo "<br>With formatting = ".number_format($number,3,'.','#'); //2#512#589.668
// Two decimal place, ',' as decimal separator and : as thousand separator
echo "<br>With formatting = ".number_format($number,2,',',':'); //2:512:589,67
// Two decimal place, '.' as decimal separator and , as thousand separator
echo "<br>With formatting = ".number_format($number,2,'.',','); //2,512,589.67
?>
string number_format(float $num, int $decimals = 0, ?string $decimal_separator = ".", ?string $thousands_separator = ",")
The function rounds while formatting and returns a string.
Use round() when you need a rounded numeric value. Use number_format() when you need presentation formatting such as decimal and thousands separators.
From PHP 8.3, a negative $decimals value rounds digits before the decimal point.
echo number_format(1234.5678, -2); // 1,200
$amount = 1234567.89;
echo number_format($amount, 2, '.', ',') . ' USD'; // Output: 1,234,567.89 USD
$number = -123456.789;
echo number_format($number, 2, '.', ','); // Output: -123,456.79
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.