Format a float to two decimal places

前端 未结 4 1890
迷失自我
迷失自我 2020-12-17 07:35

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

相关标签:
4条回答
  • 2020-12-17 08:16

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

    0 讨论(0)
  • 2020-12-17 08:33

    Try number_format:

    echo number_format("5.2",2)
    
    0 讨论(0)
  • 2020-12-17 08:36

    Try this:

    number_format((float)$foo, 2, '.', '');
    
    0 讨论(0)
  • 2020-12-17 08:38

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

    0 讨论(0)
提交回复
热议问题