Tag Archives: php 2 digits after decimal

PHP number_format Function


PHP number_format Function : This function is used to format a number with grouped thousand. This function accepts one, two or four parameter not three. This function is important when you are working with the numbers. For example if you are working with price and you want to format numbers up to two digits of decimal, you can use number_format() function. Suppose you have a variable $price = “98”; if you use the function echo $formattedPrice = format_number($price,2); it will print 98.00.
We are going to describe this function with example and demo.


PHP number_format Function Syntax

Here is syntax of number_format Function

PHP number_format Function Syntax

number_format(number,decimals,dec_point,separator)

Parameters

  • number : The number you want to format. If other parameters are not set it will number with no decimal points and use thousand separator comma(,).
  • decimals : Used to set decimal points. Number will be formatted with decimal points.
  • dec_point : Separator for decimal point.
  • separator : Specifies the string for thousand separator.

Return Value

Returns the formatted number on the basis of the input parameters.

Technical Requirements

Php Version : 4+

PHP number_format Function Example 1

Here is very basic example with single parameter ie. number. PHP format number with commas is most common question here is the example of format number with comma –

PHP format number with commas

$number = "55789.99";
$formattedNumber = number_format($number);
echo $formattedNumber ;

Try it »

When you run the above example will produce the following output-

PHP number_format Function

PHP number_format Function Example 2

Here is example with single two parameters ie. number and decimal. PHP format number to 2 decimal places is also most common used example. Here is the example of format number with decimal –

PHP format number to 2 decimal places

$number = "55789.99";
$formattedNumber = number_format($number,2);
echo $formattedNumber ;

Try it »

When you run the above example will produce the following output-

PHP number_format Function Example

PHP number_format Function Example 3

Here is example with decimal point and separator –

Separator And String for Thousand Separator

$number = "55789.99";
$formattedNumber = number_format($number,2,',',' ');
echo $formattedNumber ;

Try it »

When you run the above example will produce the following output-

PHP number_format Function

In the above example there is comma instead of dot and a space separator in thousand.