I have some database figures that I am doing some simple math with. For some reason, I can’t keep the total from rounding to the nearest dollar. I need to include the cents information, as well, though. I am positive that each itemPrice entry contains two decimal places in the database.
if (strpos($row2["itemDiscount"],'%') !== false) {
$itemDiscount = $row2["itemDiscount"];
$itemDetailTotalUnformatted = $row2["itemQuantity"]*($itemPrice*(1-($itemDiscount/100)));
}
else {
$itemDetailTotalUnformatted = $row2["itemQuantity"]*($row2["itemPrice"]-$row2["itemDiscount"]);
}
$itemDetailTotal = number_format($itemDetailTotalUnformatted, 2, '.', '');
echo $itemDetailTotal;
var_dump($row2):
50.00array(6) {
[0]=>
string(1) "2"
"itemQuantity"]=>
string(1) "2"
[1]=>
string(5) "30.00"
[itemPrice]=>
string(1) "30.00"
[2]=>
string(4) "5.00"
[itemPrice]=>
string(4) "5.00"
When dealing with currency, ALWAYS work in integers. Save the prices in cents, handle prices in cents, and only at the very end do you divide by 100 to present the result.
The reason for this is that ints have perfect precision (up to obscenely high values, where they are handled as floats instead), whereas floats do not. There is no fixed-point type in PHP.
Once you do that, your rounding problems will probably disappear.