Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Problem with float values
  • Hey,

    i try to store a float value (example 0.00039803) in my mysql database.
    i use the fuelphp orm but for some reason fuelphp stores the value as 0.000398 ...

    Any idea why?

  • How did you define the database column? 

    Are you using Observer_Typing with defined decimals of float format on the field in the model?
  • i tried decimal 16,8 & float ... tried to floatval the value before persist it via ORM / DB::update.

    No iam not tried Observer_Typing because the problem occurs even if i use DB::update

  • Enable the profiler in the config, and enable database profiling in your db config, and check what SQL is exactly generation. Then at least you'll know if it is a Fuel issue or a MySQL issue.

    I personally try to avoid floats at all costs, as floats are always stored as an approximation.
  • I tried decimal 16,8 to but same problem ;)
  • What does the SQL in the profiler show you?
  • Hey,

    INSERT INTO `user_deposits` (`amount`, `status`, `network_confirmations`, `txid`, `confirmed`, `credited`, `credited_at`, `created_at`, `updated_at`) VALUES (0.000398, 'waiting_for_confirmations', 152, 'f4221e739c0ddd8358a180fc2e47340f96ef22eca140079d6f2f124670705630', 1, 0, 0, 1527245735, 1527245735)

    fuelphp debug says

    Variable #1:
    (Array, 12 elements) ↵
    amount (Float): 0.00039803
    confirmations (Integer): 152

    Ok, maybe its my fault ..

    i think i have to convert the float value to x and than save it to db ...
  • Will,

    $user_deposit->amount = number_format($transaction['amount'], 8);

    do the job?

    i mean can i trust this value?
  • I'll have a look later today. This is a normal DB::insert(), or is this an ORM insert?
  • Problem found.

    The DBAL does a sprintf("%F", $val) to convert the float into a locale-agnostic float, as PHP uses decimal comma's in some locale's which most databases don't like. And for some reason that truncates.

    Next up: a solution...
  • Think I fixed it.

    $val = 0.000398036536274371421812;
    $query = DB::insert('test', array('value'))->values($val))->execute();

    stores 0.000398037 in a MySQL column defined as "float" without any decimals.

    The ORM has a similar issue in the Typing observer, so fixed that too.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion