Xander
Xander

Reputation: 397

Format a number with PHP to always have 2 digits before decimal

I'm trying to format a number in PHP to always have at least 2 places before the decimal and can't seem to figure it out no matter what I google/try. I'd prefer to only do this if there's not a whole number before the decimal.

This would be the ideal desired output, as I do not know the numbers before hand, it changes per page.

0.59 becomes 00.59
1.00 stays 1.00
0.43 becomes 00.43
14.56 stays 14.56

Any ideas?

Upvotes: 0

Views: 3608

Answers (3)

Alan Horrocks
Alan Horrocks

Reputation: 324

If you're not on Windows, this works:

$num = 0.59;
echo trim(money_format("%=0#2.2n", (float)$num));

You might also need to add the ! flag if you get the currency symbol in the output.

See php.net/money_format

Upvotes: 1

Svea
Svea

Reputation: 257

Add a 0 if the number is less than 1:

$res = (($num < 1) ? '0' : '').number_format($num, 2);

Upvotes: 1

SamyQc
SamyQc

Reputation: 365

Here's a way to do what you want :

$num = 0.342;
$num = number_format(round((float) $num, 2),2);
if ($num < 1) $num = str_pad($num,5,'0',STR_PAD_LEFT);
echo $num;

Upvotes: 1

Related Questions