Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a float value when dividing two integers? (PHP)

Tags:

Hi I am trying to divide two integers ex: 12/13 but I always get a whole integer 1 not a decimal number.

I tried type casting the values to float before hand with no success.

Basically all I want is a decimal result like: 0.923...

$x = 12; $y = 13; echo $value = $x / $y; //Would like to see 0.923 not 1 
like image 962
user1869257 Avatar asked Jun 20 '13 15:06

user1869257


People also ask

How do you find the float value by dividing two integers?

Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f; should give you the result you want.

How do you divide with float?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.

Can integer be divided by float?

If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.


1 Answers

Under normal circumstances your code should return the floating value 0.923076...

The reason you get a rounded integer might be because you have your ini setting for "precision" set to 0, to fix this either edit your php.ini or use ini_set("precision", 3); in your code before the calculation.

Another way to workaround this is to use BCmath:

echo $value=bcdiv($a, $b, 3); 

And yet another way without using any extension is to use a little math trick by multiplying the value you want to divide by 1000 to get 3 decimals.
This way you'll divide 12000 by 13 and the whole part will be 923, then since you multiplied by 1e3 insert a comma/dot before the last most 3 places.

function divideFloat($a, $b, $precision=3) {     $a*=pow(10, $precision);     $result=(int)($a / $b);     if (strlen($result)==$precision) return '0.' . $result;     else return preg_replace('/(\d{' . $precision . '})$/', '.\1', $result); } 

echo divideFloat($a, $b); // 0.923

like image 115
CSᵠ Avatar answered Jan 16 '23 20:01

CSᵠ