Discrepancy between BASIC INT and PHP int, how to resolve?

68 Views Asked by At

I've been re-writing a BASIC program to PHP. I've run across a problem, let me explain:

In the BASIC code I have the following statement with values:

LSLATVER=1590
PITCHVER=50

NRSLATHOR=INT(LSLATVER/PITCHVER-.8)
// output: 30

In PHP the code I have two examples like this:

$length_vertical_slat = 1590;
$vertical_pitch = 50;    

echo $number_of_horizontal_slats = (int) ($length_vertical_slat / $vertical_pitch - .8);
// output: 31

echo $number_of_horizontal_slats = (int) ($length_vertical_slat / ($vertical_pitch - .8));
// output: 32

Why is there such a huge difference between the 3 examples? I need the PHP to output a value of 30 in this example but I do not see how to go about it. Please help ty!

1

There are 1 best solutions below

1
On

The BASIC is using integer division, as well as reducing the final result to an int, so you'll want to mimic this in PHP (PHP converts to float by default, rather than reducing to an int).

This means that at BOTH stages (the division, and the subtraction) you'll want to reduce the value to an int. The PHP docs recommend doing this by casting to an int, like you did in your examples:

$length_vertical_slat = 1590;
$vertical_pitch = 50;    

// outputs 30
echo $number_of_horizontal_slats = (int)((int)($length_vertical_slat / $vertical_pitch) - .8);

From the PHP docs:

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, [...]