Reputation: 95
Doing what should be a straight forward calculation in PHP 7. The following never produces a float result. Running var_dump($C)
returns int(2)
$A = 0.04;
$B = 0.20;
$C = 3*($A/$B)^2;
echo $C;
I don't need the result to be float type, I need the precision.
I've tried setting the precision using ini_set('precision', n)
. I've tried the code on three environments and getting the same result. Declaring (float)
is also does not work.
What am I doing wrong?
Upvotes: 0
Views: 586
Reputation: 2007
try using
<?php
$A = 0.04;
$B = 0.20;
$C = 3 * pow(($A/$B),2);
echo $C; //output: 0.36
Upvotes: 0
Reputation: 3568
^
does not calculate the power, but XOR (which casts float to int).
to calculate the power, use pow()
or in PHP5.6+ **
<?php
$A = 0.04;
$B = 0.20;
$C = 3*($A/$B)**2;
echo $C; //output: 0.12
Upvotes: 1
Reputation: 8618
You should use pow() instead.
$C = 3 * pow(($A/$B), 2);
var_dump($C); // float(0.12)
Upvotes: 0
Reputation: 535
3*($A/$B)^2
Means 3 * (A/B) XOR 2
(^
means xor
) so bascially the result you are seeing is the result of a bitwise XOR on the result of your division.
If you want to raise the result to the power 2, you should use the pow()
function. You can read about it here: http://php.net/manual/en/function.pow.php .
Upvotes: 1