Domanda

I am developing a PHP caluclator and I need a clarificator or any other method to do the step which I did now. Below is my situation and solution which I developed.

Lets see I am MULTIPLYING two values A,B.

$a=1;
$b=9;
$c= $a * $b;
echo "Output : ".$c;
echo "<br>";
// Now dividing the Values by D.
$d=1111111111111;
$e= $c / $d;
echo "Output after Division : ".$e;

Output after Division : 8.1000000000008E-12

I am sure, the output is not an integer return,its a floating value.

My problem begins here I want to inform the user that the output is a floating point not an exact integer

// So below I have made a logic to do it.
if (strpos($e,'E') !== false) {
    echo 'The returned output is an Floating Value: ';
}

My Question: Is there any other way to do it? not by checking the output contains the string 'E'. Some thing like the internal PHP returns some vale that ahs to be catched here and show to the user.

Advice me if I am doing any thing wrong.! or is there any ways to do this?

È stato utile?

Soluzione

If you want to check, that the value is close to integer, you can try this:

<?php
$tolerance = 1E-6;

$result =  8.1E-12 + 2;
if (($result % 1) < $tolerance)
{
    print "$result is close to integer ". (int) $result;
}

Prints:

2.0000000000081 is close to integer 2

Altri suggerimenti

Apart from beeing horrible code, I think the function you look for is

bool is_float ( mixed $var )

(http://wwwphp.net/manual/function.is-float.php)

EDIT: like so

if ($e % 1 !== 0) {
 echo 'The returned output is an Floating Value: ';
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top