Hướng dẫn php divide without decimal

The thing i want to do is :

   $numbertodivise = 500;

   500 / 3 = 166,66

I want to divise the number in the most equitable part and the last part to add the difference , exemple :

  500 / 3 will give me :
  $result1 = 166
  $result2 = 166
  $result3 = 168

i want the code for every division how is the best way to do that ?

asked Dec 15, 2017 at 12:26

2

Here I have extracted the remainder of the numbertodivise e.g. 2 if modulus with 3, and later I divided and extracted the integer part of the division so that I can add the remainder into last divided number i.e. 166 in this case.


Output will look like this:

Array
[
    [0] => 166
    [1] => 166
    [2] => 168
]

For making variables as you mentioned use:


Jay Blanchard

33.6k16 gold badges73 silver badges113 bronze badges

answered Dec 15, 2017 at 12:36

pravindot17pravindot17

1,1651 gold badge15 silver badges31 bronze badges

2

For PHP 7, you can use this function [check comment for 166 [2] => 168 ]

answered Dec 15, 2017 at 12:37

FirstOneFirstOne

5,6415 gold badges25 silver badges45 bronze badges

A method that does not loop and uses basic PHP functions.

I use array_fill to fill the array with the floor of the calculation.
Then I add the remainder to the last item in the array.

$number = 500;
$divise =3;

$arr = array_fill[0, $divise, floor[$number/$divise]];
$arr[count[$arr]-1] += $number-[floor[$number/$divise]*$divise];
// Above line can also be . $arr[count[$arr]-1] += $number-$arr[0]*$divise;
Var_dump[$arr];

//3v4l.org/hFrDc

answered Dec 15, 2017 at 13:18

AndreasAndreas

23.4k5 gold badges29 silver badges62 bronze badges

This is a way to do it using intval[] and the modulo operator %:


The result of which will be:

This is result1: 166
This is result2: 166
This is result3: 168

answered Dec 15, 2017 at 13:05

Ivan86Ivan86

5,6372 gold badges13 silver badges30 bronze badges

5

Chủ Đề