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"
?>/* www  .j a  v  a  2s.co  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"
?>//from w w w .  j  a  v  a2s.  c  om

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"
?>//from   ww  w .  jav  a 2 s .c o m

Result

Related Topic