PHP, Format Number to have always have 2 decimal places

In PHP I have decimal numbers that may or may not have trailing zeros.

For example

 1
 1.1
43.87

How do I make sure that all these numbers have exactly two decimal places like this:

 1.00
 1.10
43.87

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You should use number_format():

number_format(1.1, 2);

Solution 2

For laravel:

{!! number_format((float)($item->amount), 2) !!}

For Raw PHP:

number_format((float)($yourVariable), 2)

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply