Format Number to 2 Decimal Places in PHP

Using the round() function

To format a number to 2 decimal places in PHP, you can use the round() function and pass the number and 2 as arguments to the round() function.

Here is an example of how to use the round() function to format a number to 2 decimal places:

Output

round() function accepts a number and the number of decimal places to round to as arguments, and it returns the rounded number as a float.

Using the number_format() function

To format a number to 2 decimal places in PHP, you can use the number_format() function. number_format() formats number with specified decimal places.

Here is an example of how to use the number_format function to format a number to 2 decimal places:

Output

We used number_format() to format number to 2 decimal places in PHP.

number_format() function accepts 4 arguments:

  • the number to format,
  • the number of decimal places to include, and
  • the decimal point character to use.
  • thousand separator which is not applicable here.

Use sprintf() function

To format a number to 2 decimal places in PHP, you can also use the sprintf() function and use the format string "%0.2f".

Here is an example of how to use the sprintf function to format a number to 2 decimal places:

Output

sprintf() function accepts a format string as its first argument, and it formats the numbers that are passed as subsequent arguments according to the specified format.

Use the floatval and number_format function

To format a number to 2 decimal places in PHP, you can also use the number_format() function in combination with the floatval() function.

You can first convert the number to a string using the floatval() function, and then use the number_format() function to format the string to 2 decimal places.

Here is an example of how to use the floatval() and number_format() functions to format a number to 2 decimal places:

Output

That’s all about how to format number to 2 decimal places in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *