简体   繁体   中英

php & maths - rounding?

Basically, I have a number:

<?
$rating = 72.7777777778;
?>

I basically want to do some maths to create this number as 80.

If the number was 62.7777777778 , the number would be 60.

I want the numbers rounded like so:

20, 40, 60, 80, 100

So say I have three numbers:

36.999, 47, 91

I would get:

40, 40, 100

How do I go about doing this? I've tried with round, ceil & floor but I haven't got anywhere.

Would it just be easier doing something like so?

if ($rating < 30){
    $rating = 20;
}elseif (($rating > 30) && ($rating < 50)){
    $rating = 40;
}elseif (($rating > 50) && ($rating < 70)){
    $rating = 60;
}elseif (($rating > 70) && ($rating < 90)){
    $rating = 80;
}else{
    $rating = 100;
}

etc...

$rounded = round(62.222 / 20) * 20;

尝试这个:

 $rating = round($rating/20.0)*20

If you want everything consistently rounded to the nearest <value> , then divide by <value> , round, and multiply by <value> .

 // replace this with 20 to get 20,40,60,80...
 // or with 7 to get 7, 14, 21, 28, 35...
 // or with...........
 $roundedBy = 10;
 $toRound = 75;
 echo 
    // 7.5 -> 8
    round( $toRound / $roundedBy )
    // 8 * 10 = 80;
    * roundedBy;

If you want to round up, replace round with ceil . If you want to round down replace round with floor .

Unfortunately, your numbers seem to be inconsistent with rounding: 36.999, 47 will round to 40 and 50 respectively.

As to your if... else statements, you can shorten them:

if ($rating < 30){
    $rating = 20;
}elseif ($rating < 50){ // will always already be >= 30
    $rating = 40;
}elseif ($rating < 70){ // will always already be >= 70
    $rating = 60;
}elseif ($rating < 90){ // will always already be >= 70
    $rating = 80;
}else{ // will always already be >= 90
    $rating = 100;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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