I'm looking for a function that would cast a numeric-string into either integer or float type depending on the content of the string, e.g. "1.23" -> float 1.23, "123" -> int 123.
I know I can use if-s with is_int, is_float and cast to appropriate types - but maybe there is a function that would do it automatically?
GG.
19.8k13 gold badges79 silver badges127 bronze badges
asked May 17, 2013 at 10:02
No, no function provides the automatic cast. However you can cast with this simple hack [the cast is automatically made by PHP in internal]:
$int = "123"+0;
$float = "1.23"+0;
for generic number:
$yourNumberCasted = $yourStringNumber + 0;
With a function:
function castToNumber[$genericStringNumber] {
return $genericStringNumber+0;
}
$yourNumberCasted = castToNumber[$yourStringNumber];
answered May 17, 2013 at 10:05
antooxantoox
1,28911 silver badges9 bronze badges
3
You can fulfil your requirement using following line.
$i = "1.23";
echo $c = [double]$i; // will return 1.23
$i = "123";
echo $c = [double]$i; // will return 123
answered May 17, 2013 at 10:23
There is no built in function to do that but you can create your own quickly.
function castNumber[$n]
{
if[!is_numeric[$n]] return 0;
return [is_float[$n]] ? [float] $n : [int] $n;
}
and use it:
$casted = castNumber[$num_to_cast];
answered May 17, 2013 at 10:11
letiagoalvesletiagoalves
11k4 gold badges38 silver badges66 bronze badges
5
None of these worked for me. But here is my solution:
$numString = '1.0';
$intOrFloat = [strpos[$numString, '.'] !==false] ? floatval[$numString] : intval[$numString];
answered May 18, 2018 at 12:49
Jan TlapákJan Tlapák
8357 silver badges9 bronze badges
1
If your incoming value is dirty [e.g.
user-provided] and so not guaranteed to be numeric, as of PHP 8.0 the accepted solution will generate Fatal error: Uncaught TypeError: Unsupported operand types: string + int
where previously it was just a warning.
You can drop an is_numeric[]
in there and provide an explicit 0 value for non-numerics
function castToNumber[$genericStringNumber] {
return is_numeric[$genericStringNumber] ? $genericStringNumber + 0 : 0
}
Alternatively you could explicitly cast with something like
function castToNumber[$genericStringNumber] {
return [[int]$genericStringNumber == [float]$genericStringNumber]
? [int]$genericStringNumber
: [float]$genericStringNumber;
}
answered Jul 5 at 8:13
There is a function
intval[]
which does almost the same thing as type-casting mentioned in other answers, however it can't be used on objects.
Also having same functionality: boolval[]
and floatval[]
.
answered May 17, 2013 at 10:10
VoitcusVoitcus
4,4394 gold badges23 silver badges40 bronze badges
2