PHP - Formatting Numbers with number_format()

Introduction

PHP's number_format() function formats numbers with thousands separators and rounded to a specified number of decimal places.

In its most basic form, pass the number to format as a single argument, and the function returns the formatted string:

Demo

<?php
   echo number_format(1234567.89); // Displays "1,234,568"
?>

Result

This rounds to the nearest whole number.

If you'd rather include some decimal places, specify the number of places as a second, optional argument:

Demo

<?php

echo number_format(1234567.89, 1); // Displays "1,234,567.9"
?>/*from   ww  w  .j a va2 s  .  c  o  m*/

Result

You can change the characters used for the decimal point and thousands separator by passing two more optional arguments.

The following code formats the number using the French convention of a comma for the decimal point and a space for the thousands separator:

Demo

<?php

echo number_format(1234567.89, 2, ",", " "); // Displays "1 234 567,89"
?>// w  w w .ja  va 2  s. com

Result

You can pass empty strings for either of these two parameters, so you can format a number with no thousands separators if you like:

Demo

<?php

echo number_format(1234567.89, 2, ".", ""); // Displays "1234567.89"
?>/*w ww .  ja v a2  s. com*/

Result

Related Topic