8

Hopefully just a quick question. I have a DECIMAL column in my database. The value is a very small decimal fraction - summing this value for all rows would equal 1.

Now I'd like to use this value in my php application, display it, perform calculations upon it and save it back to the database.

As php only has integer and float types, what is the best way to use that value in php so as not to lose any precision in calculations or display?

  • Keep the value as a string and use BC Math for calculations
  • Cast the number as float - I know php floats are precise to a good number (depending on the OS)
  • Convert the value to an integer using a function which remembers the exponent
  • Something else?

Thanks

Bendos
  • 255
  • 2
  • 11
  • Keeping it as a string would preserve the accuracy, but once you start doing math on it, all bets are off. – Marc B Feb 06 '12 at 14:35
  • 4
    I'd use [BC Math](http://www.php.net/manual/en/intro.bc.php) – N.B. Feb 06 '12 at 14:40
  • 2
    What is the complexity of the calculations you want to perform on the value? If the calculations are pretty standard, you could create a stored procedure in MySql to perform the calculations. – gavintfn Aug 01 '20 at 08:17
  • 1
    I would keep PHP as a presentation of the calculation results and perform the calculations on the database side. This gives you the advantage to show the same resultset in different applications (if needed in the future), specially if such persision is required. – Tiit Oct 29 '20 at 08:08

0 Answers0