PHP number_format() Method

PHP number_format() function is  “used to format a number with grouped thousands.”

Syntax

number_format($number, $decimals, $decimalpoint, $separator)

Parameters

  1. $number(required): It is the number is to be formatted. If no other parameters are set, the number will be formatted without the decimals and with the comma (,) as the thousands separator.
  2. $decimals(optional): It specifies the number of decimal points to use. The number will be formatted with the dot (.) notation as the decimal point if this parameter is set.
  3. $decimalpoint(optional): It specifies what string to use for a decimal point.
  4. $separator(optional): It specifies what string to use for the thousands separator.  If this parameter is provided, all other arguments must be specified.

Note: This function accepts either one, two, or four parameters, but not three.

Return value

It returns the formatted number.

Visual RepresentationVisual Representation of PHP number_format() Method

Example 1: How to Use number_format() function

<?php

$number = 5000000;

 echo number_format($number)."\n"; //Basic Formatting with No Decimals
 echo number_format($number,2)."\n"; //Formatting with Decimals
 echo number_format($number,2,",","."); //Using Custom Separators

Output

5,000,000
5,000,000.00
5.000.000,00

Example 2

If you pass anything instead of numbers, it gives a warning.

<?php
 
$str = "ELEVEN"; 

echo number_format($str);

Output

PHP Warning: number_format() expects parameter 1 to be float, string given
in /Users/krunal/Desktop/code/php/pro/app.php on line 5

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.