Search code examples
phpmathfloor

PHP math converting amounts


I am trying to convert cricket overs i.e 6 to show 0.6 and 12 to show 1.6. I got it all working except for the last part where it returns the full figure.

My code:

foreach($numberofballs as $x){
    $first = floor($x / 6);
    $last = $x - ($first * 6);
    echo $first.'.'.$last;
}

Lets assign an array for testing suppose the below array needs to be converted for this loop

$numberofballs = array(1,2,3,4,5,6);

foreach($numberofballs as $x){
    $first = floor($x / 6);
    $last = $x - ($first * 6);
    echo $first.'.'.$last;
}

/* notes
for 1 it does it right = 0.1
for 2 it does it right = 0.2
for 3 it does it right = 0.3
for 4 it does it right = 0.4
for 5 it does it right = 0.5
how its supposed to work for 6:
for 6 I do not want to get = 1 I would like to get 0.6 and no there is never 0.7
/ end notes */

I am not saying the above code is wrong, I am just wishing to get the end value correct.


Solution

  • Try something like this:

    foreach( $numberofballs as $x){
    
    
           $first = floor($x / 6);
           $last = $x - ($first * 6);
           if($last==0 && $first>0) {$last=6; $first-=1;}
           echo $first.'.'.$last;
        }