Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a numeric string as float type data

What is the PHP command that does something similar to intval(), but for decimals?

Eg. I have string "33.66" and I want to convert it to decimal value before sending it to MSSQL.

like image 808
JoHa Avatar asked Jul 26 '10 23:07

JoHa


People also ask

How do you convert a string to a number in float?

You can use the float() function to convert any data type into a floating-point number. This method only accepts one parameter. If you do not pass any argument, then the method returns 0.0. If the input string contains an argument outside the range of floating-point value, OverflowError will be generated.

Which function converts a string or int variable into a float data type?

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

Can we convert string to float in Java?

Strings can be converted to floating point numbers using different methods in Java. The different methods used to convert strings to float are: the valueOf() method, the parseFloat() method, Float class constructor, and the DecimalFormat class.

How do you float a string in Python?

In Python, we can use str() to convert float to String.


1 Answers

How about floatval()?

$f = floatval("33.66");

You can shave a few nanoseconds off of type conversions by using casting instead of a function call. But this is in the realm of micro-optimization, so don't worry about it unless you do millions of these operations per second.

$f = (float) "33.66";

I also recommend learning how to use sscanf() because sometimes it's the most convenient solution.

list($f) = sscanf("33.66", "%f");
like image 200
Bill Karwin Avatar answered Oct 08 '22 11:10

Bill Karwin