-2

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
    Have you tried with http://www.php.net/intval ? – Matteo Dec 09 '13 at 12:16
  • Read up on floating point math. For php floating point maths, use 'bcmath': http://php.net/manual/en/book.bc.php – Nanne Dec 09 '13 at 12:19
  • 3
    First thing to notice is your basic maths is out `$var/$var - $float` is not the same as `$var/($var - $float)` the brackets are evaluated first maths 101. Second thing to notice is that your hard casting it as an INT so php is doing the logica thing and rounding 30.5 to 31 to 31. Your first statement is correct but remove the hard cast – Dave Dec 09 '13 at 12:19
  • Will read. I'm a lazy coder so forgive me. FORGIVE ME!!! – TheRealWitblitz Dec 09 '13 at 12:24
  • Is it good practice in this case to also `floatval()` my $vars? – TheRealWitblitz Dec 09 '13 at 12:53

1 Answers1

1

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, [...]

Shai
  • 7,159
  • 3
  • 19
  • 22