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
  • 66,048
  • 104
  • 272
  • 428
  • 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
  • 34,563
  • 55
  • 137
  • 201
2

Use Sprintf

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

For more information, refer to the documentation of sprintf.

Venu
  • 7,243
  • 4
  • 39
  • 54
1

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

Timothée Groleau
  • 1,940
  • 13
  • 16
1

Though i would recommend number_format, you could use

sprintf('%02.2f', $price)

if you want to rely on string functions.

SomeoneYouDontKnow
  • 1,289
  • 10
  • 15