MySQL DECIMAL handling in PHP

12,621

Solution 1

The variable is probably a string initially in PHP (when read from the MySQL result object). In general, PHP's floating-point datatype cannot be relied upon to keep the precise decimal value required. You should use an arbitrary-precision mathematics library like GMP. (When you fetch a row of the result object, pass the DECIMAL column value in to the appropriate constructor, and then operate on it using the functions provided by the library you are using.)

To go more into depth: Suppose you have an amount stored in the database, in a DECIMAL(6, 4) column. You want to fetch that into PHP, to do something with it. You issue a query to fetch that column. You fetch the first row of the query into an associative array. Suppose that the value from that row is 2.5674. Your array is now something like array('MyDecimal' => '2.5674') (the number appears as a string). You use (as far as I can tell) gmp_init() to convert that string to a GMP resource. Now you can do mathematics with that number using the other GMP functions. If you want to store a GMP number, you could convert it back to string using gmp_strval() (perhaps you do not have to do this if you are using a database abstraction layer that can handle GMP resources).

Solution 2

You could try using the arbitrary precision features:

http://php.net/manual/en/book.bc.php

Your other option is to store the values as INTs and then convert them when they need to be displayed (i.e. divide by one hundred).

Share:
12,621
Alex
Author by

Alex

Updated on June 04, 2022

Comments

  • Alex
    Alex almost 2 years

    As commonly discussed, (for example here Storing 0.00001 in MySQL ) the DECIMAL data-type should be used for fields where precision / correctness is required, such as an account balance.

    I was wondering however, how PHP handles these values and, if they are internally handled as floats, if there is still a problem when reading these values from the database, doing some calculations and writing them back again. If so, how can we force PHP to keep precision in tact?