how to display number in a certain format in php

I’d like to display a number, integer or float in a uniform way like this:

if it is integer, for example 10, it should be displayed as 10.00
if it is a float already, for example 10.1, it should be displayed as 10.10
and if the float look like this 10.116, just display the first two number after the dot
regardless the left digits following the third one.

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

$formatted = sprintf("%.2f", $your_number);

Alternatively, if you just want to print it out, and don’t need it in a variable:

printf("%.2f", $your_number);

Solution 2

refer number_format

$x=number_format(10, 2);

Solution 3

check number_format()

echo number_format(10, 2); // will output 10.00

Solution 4

You can use php’s in built number_format() function. You can get more information from php.net.

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