在PHP中,Round将小数浮点到最接近的十分位


Round floats decimals to nearest tenth in PHP

在转换货币后,我得到一个看起来像2.68的浮动。

尝试用ceil($input / 10) * 10四舍五入,但这对浮点数不起作用。

那么是否有更简单的方法将浮点数舍入到最接近的十分之一?我想取2.70


对我来说更复杂的方法是在.explode浮点数,然后用ceil68四舍五入。然后将它们组合在一起。

但是如果号码是2.96呢?它需要被3.00四舍五入,所以这使得它非常复杂。

你算错了,应该先乘后除,而不是反过来:

ceil($input * 10) / 10

但这只是四舍五入。每个方向的舍入都适用于round

round($input * 10) / 10

但是等等,round有第二个参数,只是为了这个!:)

round($input, 1) // round with precision of 1 digits after the decimal point