Niharika Gupta
Niharika Gupta

Reputation: 411

Format a float to two decimal places

I want to format a float value I have to two decimal places.

For example if I have a float for a price of 5.2, I want it to be formatted as 5.20.

Upvotes: 40

Views: 77270

Answers (4)

Danura Aditya
Danura Aditya

Reputation: 73

Try this:

number_format((float)$foo, 2, '.', '');

Upvotes: 3

GBD
GBD

Reputation: 15981

Try number_format:

echo number_format("5.2",2)

Upvotes: 75

John Parker
John Parker

Reputation: 54445

If you're simply trying to ensure a number is displayed with two decimal places, you could also use number_format, or (if this is a currency value) money_format.

e.g.: echo number_format('5.2', 2);

Upvotes: 3

FluffyJack
FluffyJack

Reputation: 1732

You'll want to use printf or sprintf. You can read more about it in the php docs.

Upvotes: 5

Related Questions