Check string is float php

What is the easiest way to check if a string contains a valid float?

For example

is_string_float["1"] = true
is_string_float["1.234"] = true
is_string_float["1.2e3"] = true
is_string_float["1b2"] = false
is_string_float["aldhjsfb"] = false

asked Dec 5, 2016 at 11:51

3

The easiest way would be to use built in function is_float[]. To test if a variable is a number or a numeric string you must use is_numeric[].

answered Dec 5, 2016 at 12:02

1

If you really want to know if a string contains a float and ONLY a float you cannot use is_float[] [wrong type] or is_numeric[] [returns true for a string like "1" too] only. I'd use


instead.

answered Jul 2, 2019 at 11:50

Lenny EingLenny Eing

1311 silver badge8 bronze badges

maybe you can use a couple of functions

out of the box

function is_string_float[$string] {
    if[is_numeric[$string]] {
        $val = $string+0;

        return is_float[$val];
    } 
      
    return false;
}

answered Dec 5, 2016 at 11:57

donald123donald123

5,4583 gold badges24 silver badges23 bronze badges

2

This can easily be achieved by double casting.

/**
 * @param string $text
 * @return bool
 */
function is_string_float[string $text]: bool
{
    return $text === [string] [float] $text;
}

answered Oct 5, 2021 at 9:35

1

Not the answer you're looking for? Browse other questions tagged php string floating-point or ask your own question.

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!?

asked Aug 7, 2012 at 15:54

1

// 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
}

answered Aug 7, 2012 at 16:02

4

This will omit integer values represented as strings:

if[is_numeric[$num] && strpos[$num, "."] !== false]
{
    $this->print_half_star[];
}

answered Aug 7, 2012 at 16:01

JK.JK.

5,0861 gold badge26 silver badges26 bronze badges

1

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]

answered Aug 7, 2012 at 16:02

FlorentFlorent

12.3k10 gold badges46 silver badges58 bronze badges

1

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

answered Nov 28, 2018 at 19:27

Why not use the magic of regular expression

Chủ Đề