38

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
Niharika Gupta
  • 401
  • 1
  • 4
  • 6

4 Answers4

72

Try number_format:

echo number_format("5.2",2)
user229044
  • 232,980
  • 40
  • 330
  • 338
GBD
  • 15,847
  • 2
  • 46
  • 50
  • 1
    [This might also be helpful.](http://php.net/manual/en/function.money-format.php) – FluffyJack Sep 15 '12 at 07:52
  • 5
    Keep in mind that number_format returns a string, so your float will no longer be of type float. if you try and use the resulting number in calculations you may get undesirable results. You can cast it back to a float by wrapping it in floatval() – Baxny Mar 23 '15 at 11:07
  • 1
    Note: `+number_format("5.2",2);` will give you a number as opposed to `number_format("5.2",2)` which gives a string. Anyways, `sprintf('%0.2f', $num)` has always been my preference in general situations. Never had a valid reason to do a benchmark test, let me know in case you have a valid reason to use otherwise except personal preference(or context). Cheers! – Fr0zenFyr Sep 12 '15 at 20:45
  • 1
    Note: number_format will round up your numbers... for example number_format('21.188624', 2, ',', ' ') is 21,19. https://stackoverflow.com/questions/3833137/how-to-make-number-format-not-to-round-numbers-up – syoels Sep 13 '17 at 09:32
  • IMPORTANT: If you want to do calculations with the result, as Baxny mentioned, casting `number_format(n > 999, 2)` will result in `1`. You can't cast or calculate a number string with a comma in it, so make sure to remove that: `number_format('5.2', 2, '.', '');` – ShaneOH Sep 28 '17 at 17:31
5

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

FluffyJack
  • 1,732
  • 10
  • 15
3

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);

John Parker
  • 54,048
  • 11
  • 129
  • 129
3

Try this:

number_format((float)$foo, 2, '.', '');
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
  • Please consider editing your answer to include an explanation of how your code solves the problem at hand. – Matt Jul 11 '16 at 17:45
  • @Matt this answer is good enough.. look at the top answer its exactely the same... – Fipsi Aug 30 '18 at 08:19