Reputation: 379
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.
Upvotes: 1
Views: 2366
Reputation: 39704
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
Upvotes: 3
Reputation: 1002
You can convert the string to a float with
floatval($stringVar)
PHP's supports mathematical operators.
So if you have $a and $b.
$a + $b;
$a - $b;
$a * $b;
$a / $b;
$a % $b;
Upvotes: 0
Reputation: 4819
Get the variables out of MySQL, and then you can perform simple arithmatic as per this manual page: http://php.net/manual/en/language.types.float.php
For instance
$a = '0.002';
$b = '1.1';
echo $c = $a + $b; // Outputs 1.1002
Upvotes: 0