How should i use MySQL Decimal data type in php?

Hope just a quick question. I have a DECIMAL column in my database. The value is a very small decimal fraction - the summation of this value for all lines will be 1.

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

Since php has only integer and float types, what is the best way to use this value in php so as not to lose accuracy in calculations or display?

  • Save the value as a string and use BC Math for calculations
  • Enter a number as a float - I know php floats are accurate for a good number (depending on OS)
  • Convert a value to an integer using a function that stores the exponent
  • Something else?

thanks

+6
source share
1 answer

You must go float so as not to lose the accuracy of the calculation and use number_format to display ...

Notes:
It really depends on your needs and how you want your result to be processed if you just want to cut the mantissa after the second number or do some rounding.

Using BC math with a scale of 2, for example 2.10/1.10 , produce 1.90 using number_format(2.10/1.10, 2) will result in 1.91 (rounding the results is exactly the same as SELECT CAST(2.10/1.10 as DECIMAL(10,2)) )

Update:. As indicated in the comments, there may be times when you lose accuracy. It is probably best to do calculations with arbitrary precision in MySQL itself, so you can be sure that nothing is freed up during mathematical operations.

0
source

Source: https://habr.com/ru/post/907773/


All Articles