Search code examples
phpmysqlmathdecimalsqldatatypes

Mathematical operations on MySQL DECIMAL data type in PHP


I am storing money values on a MySQL table and I'm using DECIMAL as the data type. I need to grab these elements, do some basic mathematical operations on these values (addition, subtraction, sums, etc.), display the results to the user, and place them in a separate table. I know that MySQL allows you to do addition and sums within a table, but is there any way to do it as a PHP variable? I know in PHP you can use intval() to convert a string number to an integer, but that loses the decimal values in the conversion. Something similar would work for me because I can always convert it back to a string and enter it back in a different MySQL table.


Solution

  • PHP has (int) for integer and (float) for your problem.

    PHP can do mathematical operations (+,-,*,/,%) without defining the type and without any problems

    $var1 = 1.56;
    $var2 = 0.34;
    $sum = $var1+$var2; // 1.90