user2738640
user2738640

Reputation: 1227

PHP code returns value in float

In the following code, why does $final returns value as float?

When the calculated value is 6, it should return as integer, otherwise float.

How can I do that?

$x = 62;
$round = 5 * round($x / 5);
$final = $round/10;     
var_dump($final); 
float(6) 

Edit: Sorry if my question is not clear. I need to find out if the $final has any decimal value or not. So in order to find out that, I was using is_float function, but that always returns true because above variable returns the value in float always. Hope my question is a bit more clear.

Upvotes: 0

Views: 486

Answers (4)

djot
djot

Reputation: 2947

See this code live here:

http://sandbox.onlinephpfunctions.com/code/f8f383604cf848ab63534da69295f8482528e4ce

-

<?php

    $final = function($num) {

      $calc = (5 * ($num / 5)) / 10;

      if (intval($calc) == $calc) { settype($calc, "integer"); }
      else { settype($calc, "float"); } // might not need that line
      return $calc;
    };

    var_dump($final(62)); print '<br />';
    var_dump($final(60)); print '<br />';
    var_dump($final(59)); print '<br />';

?>

Besides, in the OPs code, this line (the round())is incorrect:

$round = 5 * round($x / 5);

Upvotes: 1

Daryl Gill
Daryl Gill

Reputation: 5524

Little bit long, but something like this should do the trick

function ReturnType($FinalVal){
 switch (gettype($FinalVal)){
  case 'integer':
     return (int) $FinalVal;
  case 'double':
    return (float) $FinalVal;

 }
}

 $x = 62;
$round = 5 * round($x / 5);
$final = $round/10;     
$Value = ReturnType($final);

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157967

The return type of round is float, as the manual states. You need to cast the result to integer:

$result = (integer) round($value);

Update:

Although I think a method should return either floats or integers and not change this depending on the result's value, you could try something like this:

if((integer) $result == $result) {
    $result = (integer) $result;
}
return $result;

Upvotes: 2

david
david

Reputation: 3218

You must casting like this

$round = 5 * (int)(round($x / 5));

round($x / 5) returns float. If you don't cast it to int then the result would be float

Upvotes: -1

Related Questions