简体   繁体   English

使用PHP将舍入数字逼近0.2

[英]round number to nearest 0.2 with PHP

I'm creating this rating system using 5-edged stars. 我正在使用五角星创建这个评级系统。 And I want the heading to include the average rating. 我希望标题包括平均评级。 So I've created stars showing 1/5ths. 所以我创造了显示1/5的星星。 Using "1.2" I'll get a full star and one point on the next star and so on... 使用“1.2”我将获得一颗满星并在下一颗恒星上获得一分等等......

But I haven't found a good way to round up to the closest .2... I figured I could multiply by 10, then round of, and then run a switch to round 1 up to 2, 3 up to 4 and so on. 但是我还没有找到一个很好的方法来最接近最接近的.2 ......我想我可以乘以10,然后是一轮,然后再转到第1轮到第2轮,第3轮到第4轮等等。上。 But that seems tedious and unnecessary... 但这似乎乏味且不必要......

round(3.78 * 5) / 5 = 3.8

A flexible solution 灵活的解决方案

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 );
function round2($original) {
    $times5 = $original * 5;
    return round($times5) / 5;
}

So your total is 25, would it be possible to not use floats and use 1->25/25? 所以你的总数是25,是否可以不使用花车并使用1-> 25/25? That way there is less calculations needed... (if any at all) 这样就需要更少的计算......(如果有的话)

Why is everyone giving solutions that require a deeper inspection or conversion? 为什么每个人都提供需要更深入检查或转换的解决方案? Want 0.2? 想要0.2吗? Then: 然后:

round($n / 0.2) * 0.2; // $n = 3.78 / 0.2 = 18.9 (=) 19 * 0.2 = 3.8 //

Want 5? 想要5? Then: 然后:

round($n / 5) * 5; // $n = 17 / 5 = 3.4 (=) 3 * 5 = 15 //

It's as simple as that. 就这么简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM