Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast string to either int or float

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?

like image 609
ducin Avatar asked May 17 '13 10:05

ducin


People also ask

Can you convert string to int or float?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.

Can you cast string to float Python?

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.


1 Answers

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);
like image 112
antoox Avatar answered Oct 05 '22 03:10

antoox