0
$total_cost and $amount_paid value is 2028.36 as shown in the bottom right screenshot 
// values are from database. both are type decimal 15,2

$balance = ($total_cost - $amount_paid);

the result is 2.2737367544323E-13

The result should be 0. I tried converting both to float. still doesn't work

check screenshot below. I tried printing the value, the result shown in the bottom right corner.

enter image description here


Solved

I did the calculation in the database level instead.

$this->db->select('(SUM(ItemCost * OrderQty) - OrderAmountPaid) - Discount as Balance');
Community
  • 1
  • 1
Mark F
  • 73
  • 5
  • PHP doesn't have decimal numbers, it uses floating point, so you can have problems like this. Do the subtraction in the database. – Barmar Feb 09 '18 at 01:31
  • https://ideone.com/4E8LVq i get 0 –  Feb 09 '18 at 01:35
  • @AbraCadaver Hi bro, i have added the image. as you could see. the code is just simple substraction of total cost and amount paid. but the result was like that. i even debug as you could see in the right bottom image. – Mark F Feb 09 '18 at 01:35
  • Do not use floating point numbers to represent currency because of problems exactly like this. Use a library that does it properly, like [MoneyPHP](https://packagist.org/packages/moneyphp/money). – Sammitch Feb 09 '18 at 01:45
  • You should never use PHP's default floating-point numbers (float or double) for currency operations, because their results are approximate. Instead, use PHP's BCMath module ( http://php.net/manual/en/book.bc.php ) to get exact numbers, or perform the calculation directly in MySQL on data with a type of DECIMAL. – Max Feb 09 '18 at 01:50
  • @Max Thank you very much for the suggestion. I've did the calculation in the database level instead and it works great – Mark F Feb 09 '18 at 04:00

0 Answers0