How do you convert input to float in python?

Home » Python

Python | read/take input as a float: Here, we are going to learn how to read input as a float in Python?
Submitted by IncludeHelp, on April 02, 2019

To take input in Python, we use input() function, it asks for an input from the user and returns a string value, no matter what value you have entered, all values will be considered as strings values.

Consider the following example,

# python code to demonstrate example
# of input() function

val1 = input("Enter any value: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))

val2 = input("Enter another value: ")
print("value of val2: ", val2)
print("type of val2: ", type(val2))

val3 = input("Enter another value: ")
print("value of val3: ", val3)
print("type of val3: ", type(val3))

Output

Enter any value: 10
value of val1:  10
type of val1:  <class 'str'>
Enter another value: 10.23
value of val2:  10.23
type of val2:  <class 'str'>
Enter another value: Hello
value of val3:  Hello
type of val3:  <class 'str'>

See the program and output – Here, we provided three value "10" for val1 which is an integer value but considered as a string, "10.23" for val2 which is a float value but considered as a string, "Hello" for val3 which is a string value.

How to take input as a float?

There is no such method, that can be used to take input as a float directly – but input string can be converted into a float by using float() function which accepts a string or a number and returns a float value.

Thus, we use input() function to read input and convert it into a float using float() function.

Consider the below example,

# python code to take float input

# reading a value, printing input and it's type
val1 = input("Enter any number: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))

# reading a value, converting to float
# printing value and it's type
val2 = float(input("Enter any number: "))
print("value of val2: ", val2)
print("type of val2: ", type(val2))

Output

Enter any number: 123.456
value of val1:  123.456
type of val1:  <class 'str'>
Enter any number: 789.123
value of val2:  789.123
type of val2:  <class 'float'>

Example to input two float numbers and find their sum and average

# python code to read two float numbers
# and find their addition, average

num1 = float(input("Enter first number : "))
num2 = float(input("Enter second number: "))

# addition
add = num1 + num2

# average
avg = add/2

print("addition: ", add)
print("average : ", avg)

Output

Enter first number : 123.456
Enter second number: 789.02
addition:  912.476
average :  456.238

When you take a user input in python programming while working with terminal or file operations like reading or writing a file, the input is a string object. Even though you ask for the floating-point value, the input method in python will fetch the user input as a string object. Hence, you have to explicitly convert the string into a floating-point value so that you can perform the necessary operations on it. Before understanding the methods to convert the string to float explicitly, let us first go through the strings and float data types in python.

What are strings in python?

A string is a series of characters inside the quotes. You can use single quotes or double quotes to display the string. Also, triple quotes are used to display the multi-line quotes.

As you know, that computer does not deal with characters but instead, it works only with binary numbers. Therefore, the characters you input in the system are converted into a binary format using the encoding techniques like Unicode and ASCII. In python, the string is a sequence of Unicode characters which include every character and symbol in all languages. Square brackets are used to access the string elements along with the index position of the string character. The indexing of character in a string starts from ‘0’, and therefore, the string's first character always has the index equal to zero.

For Example

# defining strings in Python
s = 'Favtutor'
print(s)

s = "Favtutor"
print(s)

s = '''Favtutor'''
print(s)

# multi-line string
s = """Compile with
    Favtutor"""
print(s)

Output

Favtutor
Favtutor
Favtutor
Compile with
    Favtutor

What is Float in python?

Float is one of the data types of python programming that is used to represent the floating-point number. Float is always written with the decimal points by dividing the integer and fractional parts. IEEE 754 standard represents the float as 64-bit double-precision values. Therefore you can say that the floating-point numbers are represented internally as binary(base-2) fractions. The maximum value of any floating-point number can be approximately 1.8 x 10308. If any number is greater than this, you can indicate them by the string ‘inf’ in Python

For Example

a = 3.14
print(type(a))
print(a)

Output

Convert String to Float in Python

Below are 6 common and simple methods used to convert a string to float in python

1) Using float() function

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.

For Example

s = '10.123'
f = float(s)
print('Float Value =', f)

Output

If the input string contains anything other than a floating-point representation of a number, the output will be ValueError. Let us understand this in detail below.

2) Convert a Number String with commas into a floating-point object

Consider that the input string is ’1,0.123'. As you can see, the string contains numbers, but it also has a comma in it. Therefore, converting this kind of string into a floating-point value is very tricky. If you directly call the float() method, then the output will raise an error.

For Example

s = '1,0.123'
f = float(s)
print('Float Value =', f)

Output

ValueError: could not convert string to float: '1,0.123'

You have to remove all the commas from the string before calling the float() function to solve this issue. Take a look at the example below to understand better.

For Example

s = '1,0.123'
f = float(s.replace(',',''))
print('Float Value =', f)

Output

3) Convert string to float list in python

In this method, firstly, you need to initialize the string, and later, you can use the float() and split() method to convert a string into the floating-point list, as shown below in the example.

For Example

s = "2.41, 6.81, 3.9, 10.21, 62.0"
res = [float(value) for value in s.split(', ')]
print("The float list is : " + str(res))

Output

The float list is : [2.41, 6.81, 3.9, 10.21, 62.0]

4) Convert a list of strings to float in python

The list of strings is the python list containing all elements as strings in it. To convert this list of strings into floating-point values, you have to use for loop to iterate through each item of the list. Later, you can use the float() method to convert each item into float value and then append it to the list again. Check out the below example for reference:

For Example

s = ['11.11', '22.22', '33.33', '33.44']
f = []
for item in s:
    f.append(float(item))
print(f)

Output

[11.11, 22.22, 33.33, 33.44]

5) Convert String to Float using Numpy

Numpy is one of the libraries for python programming, which supports large, multi-dimensional arrays and matrices to perform high-level mathematical operations. If you want to convert a string into float using NumPy, the first step will be to import the NumPy library using “import NumPy as np.” Later, you can use the “astype” method, an in-build method used to convert the string to a floating-point value in python.

For Example

import numpy as np
s = np.array(["1.267", "1.456", "0.012"])
f = s.astype(float)
print(f)

Output

6) Convert String to Float with Specified Decimal Points

It is often necessary to bring the precision for the number of zeros after the decimal in floating-point values. In such cases, you can use the float() method to convert a string into float value and then use the format() method to specify the number of decimal points in the float value. The syntax of the format method is as given below:

“{:.Nf}”.format(float value)

Here, N displays the number of decimal points you wish to put. If the floating-point value generated has fewer decimal points than the suggested, then zeros are added at the end to round it. Take a look at the example below for a better understanding.

Example

s = "3.14159"
f = float(s)
result = "{:.3f}".format(f)
print(result)

Output

Conclusion 

While programming, there are many situations where you have to convert one data type into another to perform the necessary operations. This article refers to the python string and float values in detail and the explicit methods used to convert strings into floating-point values. As the input method in python accepts the string object for user input, it is necessary to learn and understand these methods to convert the string into float data type to perform different operations on user data.

Can you float an input in Python?

Python programming language has many inbuilt libraries and functions. One among them is the float() function. With the help of the float() function, we can convert an input string or an integer value to a floating point value.

How do you convert int to float?

Converting Integers to Floats.
Python's method float() will convert integers to floats. To use this function, add an integer inside of the parentheses:.
In this case, 57 will be converted to 57.0 ..
You can also use this with a variable. ... .
By using the float() function, we can convert integers to floats..

How do you convert a string to a float?

Let's see the simple example of converting String to float in java..
public class StringToFloatExample{.
public static void main(String args[]){.
String s="23.6";.
float f=Float.parseFloat("23.6");.
System.out.println(f);.

Which function convert any input type into a float type?

The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.

Tải thêm tài liệu liên quan đến bài viết How do you convert input to float in python?