Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string is a double or not

Tags:

php

I am trying to check in php if a string is a double or not.

Here is my code:

   if(floatval($num)){
         $this->print_half_star();
    }

$num is a string..The problem is that even when there is an int it gives true. Is there a way to check if it is a float and not an int!?

like image 344
Dmitry Makovetskiyd Avatar asked Aug 07 '12 15:08

Dmitry Makovetskiyd


4 Answers

// Try to convert the string to a float
$floatVal = floatval($num);
// If the parsing succeeded and the value is not equivalent to an int
if($floatVal && intval($floatVal) != $floatVal)
{
    // $num is a float
}
like image 150
Samuel Avatar answered Oct 19 '22 08:10

Samuel


This will omit integer values represented as strings:

if(is_numeric($num) && strpos($num, ".") !== false)
{
    $this->print_half_star();
}
like image 28
JK. Avatar answered Oct 19 '22 09:10

JK.


You can try this:

function isfloat($num) {
    return is_float($num) || is_numeric($num) && ((float) $num != (int) $num);
}

var_dump(isfloat(10));     // bool(false)
var_dump(isfloat(10.5));   // bool(true)
var_dump(isfloat("10"));   // bool(false)
var_dump(isfloat("10.5")); // bool(true)
like image 7
Florent Avatar answered Oct 19 '22 08:10

Florent


You could just check if the value is numeric, and then check for a decimal point, so...

if(is_numeric($val) && stripos($val,'.') !== false)
{
    //definitely a float
}

It doesn't handle scientific notation very well though, so you may have to handle that manually by looking for e

like image 1
EyeOfTheHawks Avatar answered Oct 19 '22 10:10

EyeOfTheHawks