0

The following code need to increase 2,9 during 10 times to achieve 27 in total. my code is just increase 2,9 every time and not respect the difference in the last item on array how can I solve it ? thank you.

result of the following code:

    Array ( [0] => 2.9 [1] => 5.8 [2] => 8.7 [3] => 11.6 [4] => 14.5 [5] => 17.4 [6] => 20.3 [7] => 23.2 [8] => 26.1 [9] => 29 )

.

and it should be:

 Array ( [0] => 2.9 [1] => 5.8 [2] => 8.7 [3] => 11.6 [4] => 14.5 [5] => 17.4 [6] => 20.3 [7] => 23.2 [8] => 26.1 [9] => 27 )

.

Code:

$horas_totais = 27;
$horario_dos_km = 9.3;
$getallours =[];
$rasteach = round( $horas_totais/$horario_dos_km, 1, PHP_ROUND_HALF_UP);
$tot='';
for($z=0;$z<=$horario_dos_km;$z++){
    $tot += $rasteach;
    $getallours[] = $tot;
}
$echo='<pre>';print_r($getallours);$echo='</pre>';
3
  • So should the last increment be ignored? Because 26.1 + 2.9 = 29, clearly. The fact that 2.9 is rounded up makes it so you can't reach exactly 27. Commented Feb 23, 2019 at 16:02
  • it shoul be ignored and replca in it place 27, that the point that i have no idea how can be handle. i have to receive it from calulation ond not just replace number 27 Commented Feb 23, 2019 at 16:05
  • Welcome to 'real numbers (floating point numbers)'. Everyone gets confused by this. see Is floating point math broken?. Please go through it carefully. They will bite you. For example: You never test for real numbers to be equal! It will fail when you can see they are equal. ;-/ Never use them for money values! Never ever! Commented Feb 23, 2019 at 22:08

2 Answers 2

1

You can simply loop up to the last but one occurrence, and then add your final value manually:

for ($z = 0; $z < $horario_dos_km - 1; $z++) {
  $tot += $rasteach;
  $getallours[] = $tot;
}
$getallours[] = $horas_totais;

Note that $tot = ''; should be $tot = 0; (it does "work" with the empty string but should generate a warning).

Demo: https://3v4l.org/D6pGQ

Sign up to request clarification or add additional context in comments.

Comments

0

you can also use an if condition in the loop.

<?php
 $horas_totais = 27;
 $horario_dos_km = 9.3;
 $getallours = [];
 $rasteach = round($horas_totais / $horario_dos_km, 1, PHP_ROUND_HALF_UP);
 $tot = 0;
 for ($z = 0; $z < $horario_dos_km; $z++) {
    $tot += $rasteach;
    if($tot>27){
     $tot = 27;
    }
   $getallours[] = $tot;
 }

print_r($getallours);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.