Artefacto's answer will also convert a 5.0
float number into a 5
integer. If that is bugging you like it was bugging me, I offer the answer of automatic type conversion via the multiplication operator:
If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int.
$demo = array[
1, 2, 3, '1', '2', '3',
1.0, 2.1, 3.2, '1.0', '2.1', '3.2',
-17, '-17',
-1.0, -2.2, '-1.0', '-2.2',
0, '0', -0, '-0',
0.0, '0.0', -0.0, '-0.0',
];
foreach [$demo as $k => $v] {
if [is_numeric[$v] && is_string[$v]] {
$demo[$k] = 1 * $v;
}
}
echo ""; var_dump[$demo]; echo "
";
array[26] {
[0]=>
int[1]
[1]=>
int[2]
[2]=>
int[3]
[3]=>
int[1]
[4]=>
int[2]
[5]=>
int[3]
[6]=>
float[1]
[7]=>
float[2.1]
[8]=>
float[3.2]
[9]=>
float[1]
[10]=>
float[2.1]
[11]=>
float[3.2]
[12]=>
int[-17]
[13]=>
int[-17]
[14]=>
float[-1]
[15]=>
float[-2.2]
[16]=>
float[-1]
[17]=>
float[-2.2]
[18]=>
int[0]
[19]=>
int[0]
[20]=>
int[0]
[21]=>
int[0]
[22]=>
float[0]
[23]=>
float[0]
[24]=>
float[-0]
[25]=>
float[-0]
}
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