Jump to content

float precision error


vurentjie

Recommended Posts

hi,

 

i have a calculation that checks for minor cent precision differences across a number of payments.

 

there is a monthly allowance and payments are distributed according to a pro-rata calculation and should add up to the monthly allowance...

sometimes it is out by a cent or fraction of a cent

so i thought i could check the difference between the allowance and the total that has been paid,

 

    //basic calc

  $diff = $allowance - $total_paid;

  if($diff >0)....
  if($diff <0)...


 

  the actual arithmetic is simple enough

but i am getting precision errors

if i echo it out i can get the following

//without applying any rounding

2835.75 - 2835.75 = 4.54747350886E-13

 

any advice?

i calculate the total_paid in a loop

 


loop start
  $total_paid += $payment;  //$payment does NOT get rounded either 
loop end

 

 

the allowance is a figure a get from the database

i cast this value to float before using it, but it is only there for checking against really.

 

i only round figures after all calculations and only for display with php's number_format.

 

 

Link to comment
https://forums.phpfreaks.com/topic/153592-float-precision-error/
Share on other sites

already have error_reporting on...one of the first things I set when developing...

 

Store the values as cent instead of dollars

 

Actually instead of rands.

But yes that is gonna be the fix I reckon...it is definitely a precision error.

Such a simple solution - wish I had thought of that...

 

Will check in later...

;D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.