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?
In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With