Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String into Float? [duplicate]

I'm required to covert the variable:

pi_string = "3.1415926"

into a float. Here's what I'm dealing with:

screenshot

like image 425
itzRafay Avatar asked Jul 13 '16 11:07

itzRafay


People also ask

Can you convert strings to floats?

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. Internally, the float() function calls specified object __float__() function.

What type of data type does the atof () function return?

The atof() function returns a double value that is produced by interpreting the input characters as a number. The return value is 0 if the function cannot convert the input to a value of that type.


2 Answers

Your line should be pi_float = float(pi_string)

float(pi_string) is a float value, you can not assign to it, because it is not a variable.

like image 142
Dean Fenster Avatar answered Oct 19 '22 14:10

Dean Fenster


The method float() will do this for you if pi_string = "3.1415926".

>>>pi_float = float(pi_string)
>>>type(pi_float)
<class 'float'>
like image 5
Clíodhna Avatar answered Oct 19 '22 13:10

Clíodhna