Wednesday, July 22, 2009

PHP and type casting

I was going through some of my notes and found an issue that gave me some trouble. About a year ago I was working on a custom shopping cart, and ran into trouble with PHP's type casting. I was multiplying a float (price) by an int (quantity) and PHP was converting the float to an int by dropping the decimal part of the number before doing the multiplication. Obviously this was causing trouble with the total price charged. The fix was to force the int to a float before the multiplication.
$lineTotal = (float) $price * $quantity;