How to display number to two decimal places in PHP

How to display number to two decimal places in PHP

To display a number with two decimal places in PHP, you can use the number_format() function. Here’s an example:

$number = 123.456789;

$formattedNumber = number_format($number, 2);

echo $formattedNumber;

In this example, we have a number $number with several decimal places.

We use the number_format() function to format the number with two decimal places. The first argument is the number to be formatted, and the second argument is the number of decimal places to display.

The number_format() function returns a formatted string representation of the number.

Finally, we echo the $formattedNumber, which will display the number with two decimal places.

Output : 123.46

By default, number_format() also adds a comma as a thousands separator. If you want to exclude the thousands separator, you can specify an empty string as the third argument:

$formattedNumber = number_format($number, 2, '.', '');

This will format the number without any thousands separator.

That’s how we display a number with two decimal places in PHP.

Raad more articles on PHP here.