For converting a string to float you can use float(). Eg.float('1.2123') You can not convert '*' into float because its an operator that's why error is coming.
#observe the code
volume = float(input("Enter volume of sphere in mm^3: "))
input() = Takes input from user and stores it in string
float() = It is used to convert strings to float
Your code is volume = float(input("Enter volume of sphere in mm^3: "))
1st input() takes input from user in string then float() converts it into float.
But a = 1.4*1.0e6 there is no input() function involved thats why it's a float.
You can simply achieve your work by
volume = eval(input("Enter volume of sphere in mm^3: "))
OR
volume = input("Enter volume of sphere in mm^3: ").split("*")
volume = float(volume[0])*float(volume[1])
split(separator)- It splits a string into an array of sub-strings, by a separator string provided by user
You can read about eval from here:- Read abut eval() from here
Answer from Abhay Kumar on Stack OverflowHow to convert string to float in Python? Why is it a float when directly assigned but a string when a user inputs it? - Stack Overflow
Python string to float conversion
Is it legal/valid to use float() to convert a string containing integer to float?
convert string to float?
Videos
For converting a string to float you can use float(). Eg.float('1.2123') You can not convert '*' into float because its an operator that's why error is coming.
#observe the code
volume = float(input("Enter volume of sphere in mm^3: "))
input() = Takes input from user and stores it in string
float() = It is used to convert strings to float
Your code is volume = float(input("Enter volume of sphere in mm^3: "))
1st input() takes input from user in string then float() converts it into float.
But a = 1.4*1.0e6 there is no input() function involved thats why it's a float.
You can simply achieve your work by
volume = eval(input("Enter volume of sphere in mm^3: "))
OR
volume = input("Enter volume of sphere in mm^3: ").split("*")
volume = float(volume[0])*float(volume[1])
split(separator)- It splits a string into an array of sub-strings, by a separator string provided by user
You can read about eval from here:- Read abut eval() from here
ValueError: could not convert string to float: '1.4*1.0e6'
you try to convert formula to float. the most easy way is convert string to formula using eval
volume = eval(input("Enter volume of sphere in mm^3: "))
Hi all, I have a string a = '1721244344.700249000', I want to convert it to a floating value.
Float() is returning only 2 places after decimal point. Like 1721244344.7
Is there a way I can convert the entire string to a floating point value and get all the decimal (upto 9 places after decimal point)?
I have to use python v2.7 for this.
Edit: I do not have problem in printing the all 9 decimal places but I need the floating value so that I can subtract another value so that I get the difference with accuracy upto 9 th decimal point.