Why does PHP's sprintf not round 5s reliably?

后端 未结 3 743
梦如初夏
梦如初夏 2020-12-11 14:25

I was relying on sprintf(\'%0.1f\', 2.25) === \'2.3\' but it turns out it comes in at 2.2!

In fact it seems random:

php >         


        
3条回答
  •  悲哀的现实
    2020-12-11 15:08

    To summarise what has been said in comments in an answer:

    Because printf is not a rounding function, but a low-level function to give a string representation of a number. In this case the number internally is not the same as the number set, e.g. it might be 2.249999991231231123 because of the limitations of the floating point internal representation.

    So printf is rounding a different number to that which you entered/calculated, which is correctly 2.2 in this example.

    Therefore as the other answer (and my original question) points out, a better solution is to use round() (and possibly sprintf upon the result).

提交回复
热议问题