4
$price = 10.00;
list($dollars, $cents) = explode('.', $price);
echo $dollars . '.' . $cents;

... almost works except that the zeros are omitted. 10.00 becomes 10 and 10.10 becomes 10.1

I see there's a padding function for strings, but anything for numbers or floats?

How do I fix this?

eozzy
  • 62,241
  • 100
  • 265
  • 409
  • Maybe http://stackoverflow.com/questions/6619377/how-to-get-whole-and-decimal-part-of-a-number explanation will help? – revoua Feb 09 '13 at 10:04

4 Answers4

8

You can use number_format:

echo number_format($price, 2); // Would print 10.00

You can specify a separator for the decimal point and another one for the thousands:

echo number_format(1234.56, 2, ',', ' '); // Would print 1 234,56
Emanuil Rusev
  • 33,269
  • 52
  • 129
  • 197
2

Use Sprintf

$digit = sprintf("%02d", $digit);

For more information, refer to the documentation of sprintf.

Venu
  • 7,175
  • 4
  • 37
  • 53
1

number_format is what you want: http://php.net/manual/en/function.number-format.php

Timothée Groleau
  • 1,920
  • 13
  • 15
1

Though i would recommend number_format, you could use

sprintf('%02.2f', $price)

if you want to rely on string functions.

SomeoneYouDontKnow
  • 1,229
  • 9
  • 15