Search code examples
mysqlcodeigniterfloating-pointdouble-precision

Why won't MySQL get the correct data?


I'm using CodeIgniter's Active Record and my code is:

  $current_balance = $this->get_campaign_balance($click_report['campaign_id']);

  $campaign_ledger = array(
    'campaign_id'   =>  $click_report['campaign_id'],
    'description'   =>  "Click Deduction from script",
    'amount'        =>  -1 * $click_report['advertiser_spend'],
    'balance'       =>  "" . $current_balance - $click_report['advertiser_spend'],
    'meta_data'     =>  $click_report['day'],
    'timestamp'     =>  time()
  );

  $this->db->insert('campaign_ledger', $campaign_ledger);

When I var_dump the $campaign_ledger I get:

array(6) {
  ["campaign_id"]=>
  string(3) "277"
  ["description"]=>
  string(27) "Click Deduction from script"
  ["amount"]=>
  float(-0.05)
  ["balance"]=>
  float(89.95)
  ["meta_data"]=>
  string(10) "2012-04-19"
  ["timestamp"]=>
  int(1334881599)
}

But when the data goes into my database, the balance is 91.36800000000001 for some reason. So what's the disconnect all about?

EDIT

After changing to DECIMAL(10,4), I still get 91.3680 as an output.


Solution

  • Be careful to store currency as type "DECIMAL" in MySQL. If you use Float, you'll get inconsistent results. I know you didn't say here which data type you used, but something tells me it is probably not DECIMAL(10,2).