使用PHP将舍入数字逼近0.2

pei*_*rix 6 php math rounding

我正在使用五角星创建这个评级系统.我希望标题包括平均评级.所以我创造了显示1/5的星星.使用"1.2"我将获得一颗满星并在下一颗恒星上获得一分等等......

但是我还没有找到一个很好的方法来收集到最接近的.2 ...我想我可以乘以10,然后是一轮,然后转到第1轮到第2轮,第3轮到第4轮等等.上.但这似乎乏味且不必要......

Pet*_*ley 18

灵活的解决方案

function roundToNearestFraction( $number, $fractionAsDecimal )
{
     $factor = 1 / $fractionAsDecimal;
     return round( $number * $factor ) / $factor;
}

// Round to nearest fifth
echo roundToNearestFraction( 3.78, 1/5 );

// Round to nearest third
echo roundToNearestFraction( 3.78, 1/3 );
Run Code Online (Sandbox Code Playgroud)