Python String to Float – A Simple Illustrated Guide

Summary: To convert a string object to float object use the float(string_input) method which typecasts the string input to a floating-point value.

Introduction

Before learning how to convert a string object to a float object, let us understand what is type conversion in Python.

✎ The process of converting an object of a particular data type into another type is known as type conversion.

  • Type Conversion is of two types:
    • Implicit Type Conversion
    • Explicit Type Conversion

♻️ Implicit Type Conversion

When Python automatically converts one data type to another data type without the involvement of user, it is known as implicit type conversion.

Example: In the following code Python implicitly promotes a lower data type (integer) to a higher data type (float).

data_integer = 15  # integer object
data_float = 25.25  # float object
result = data_integer + data_float
print("result = ", result)
print("data type of result: ", type(result))

Output:

result =  40.25
data type of result:  <class 'float'>

💎 In the above example, Python automatically converts the smaller data type to a higher data type to prevent data loss. Therefore the type of the variable result is automatically float.

♻️ Explicit Type Conversion

The type of conversion in which the user has to explicitly convert an object of one type to another type is known as explicit type conversion. You have to use built-in functions like int(), str(), float(), etc., to perform explicit type conversion.

✎ Note: Explicit type conversion is also known as typecasting.

Example: The following example how you can typecast an integer to a string.

value_int = 15
value_str = str(value_int)
print("value_int: ", value_int)
print("value_str: ", value_str)
print("Type of value_int: ", type(value_int))
print("Type of value_str: ", type(value_str))

Output:

value_int:  15
value_str:  15
Type of value_int:  <class 'int'>
Type of value_str:  <class 'str'>

Now that you know what is type conversion in Python, let us proceed with our topic – “How to convert a string object to a float object?”

📌 Python float()

float(value) is a built-in function in Python that converts the argument value to a float number. For example, float('42') converts the string value '42' into the float number 42.0.

ArgumentvalueA Python object to be converted into a float number. The value object must have an __float__() method that returns the associated float number—otherwise a ValueError will be raised.
Return ValuefloatReturns a float number after converting the input argument value using its required __float__() method for the conversion.

Related Tutorial: Python float() Function

Thus, you can simply convert a string value to an floating-point value using float('value').

Example:

value_str = '99.999'  # String object
value_float = float(value_str)  # converting to float
print("value_float: ", value_float)
print("value_str: ", value_str)
print("Type of value_float: ", type(value_float))
print("Type of value_str: ", type(value_str))

Output:

value_float:  99.999
value_str:  99.999
Type of value_float:  <class 'float'>
Type of value_str:  <class 'str'>

⚠️Caution

You can only convert a numeric-string, i.e., a string containing only numbers. If you try to typecast a text string to a float object, it will lead to ValueError.

Example:

value_str = 'Finxter'  # Text String Object
value_float = float(value_str)  # converting to float
print(value_float)

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 2, in <module>
    value_float = float(value_str)  # converting to float
ValueError: could not convert string to float: 'Finxter'

📌 Python astype()

In Python, the NumPy module and the Pandas module have a method that converts one type of object into another. The name of this method is astype().

📜 Convert String to Float using astype() in NumPy

Syntax:

input_string.astype(numpy.float_)

Example:

import numpy

string_array = numpy.array(["25.25", "250.50", "2500.75"])
print()
print("Original array: ", string_array)
float_array = string_array.astype(numpy.float_)
print("Converted Array: ", float_array)
print("Type of elements within input string array: ", type(string_array[0]))
print("Type of elements within output float array: ", type(float_array[0]))

Output:

Original array:  ['25.25' '250.50' '2500.75']
Converted Array:  [  25.25  250.5  2500.75]
Type of elements within input string array:  <class 'numpy.str_'>
Type of elements within output float array:  <class 'numpy.float64'>

📜 Convert String to Float using astype() in Pandas

Syntax:

input.astype(float)

Example:

# importing pandas library
import pandas as pd

# dictionary
Data = {'Rate': ['4.47', '5', '5.98', '4.1']}
# create a dataframe
df = pd.DataFrame(Data)
# show dataframe
print(df)
print("\nBefore Conversion: ")
print(df.dtypes)
# converting to float
df['Rate'] = df['Rate'].astype(float)
print("\nAfter Conversion: ")
print(df.dtypes)

Output:

   Rate
0  4.47
1     5
2  5.98
3   4.1

Before Conversion: 
Rate    object
dtype: object

After Conversion: 
Rate    float64
dtype: object

📌 Function to Convert String to Float

You can use a function to convert a string input into a float value as shown in the following program:

Example:

def convert(x, y, cast):
    x = cast(x)
    y = cast(y)
    return x, y


num1 = input("Enter 1st number: ")
num2 = input("Enter 1st number: ")
a, b = convert(num1, num2, float)
print('Converting To Float:')
res = a + b
print("Output: ", res)
print("Type of num1: ", type(num1))
print("Type of num2: ", type(num2))
print("Type of a: ", type(a))
print("Type of b: ", type(b))
print("Type(Output): ", type(res))

Output:

Enter 1st number: 45.68
Enter 2nd number: 89.23
Converting To Float:
Output:  134.91
Type of num1:  <class 'str'>
Type of num2:  <class 'str'>
Type of a:  <class 'float'>
Type of b:  <class 'float'>
Type(Output):  <class 'float'>

If there are more than two variables that have to be converted, you can use a list as shown below.

def convert(list1, type_):
    for x in range(len(list1)):
        list1[x] = type_(list1[x])


# string inputs
a = '15.25'
b = '25.25'
c = '75.25'
li = [a, b, c]
print("Before Conversion: ", [type(number) for number in li])
convert(li, float)
print("After Conversion:", [type(number) for number in li])
print(li)
print(li[0] + li[1] + li[2])

Output:

Before Conversion:  [<class 'str'>, <class 'str'>, <class 'str'>]
After Conversion: [<class 'float'>, <class 'float'>, <class 'float'>]
[15.25, 25.25, 75.25]
115.75

❖ Python Float to String

Until now you learned how to convert a string object to a float object. Now, let us understand how we can deal the other way around, i.e., converting float to string.

📌 Method 1: Using str()

Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion.

Example:

num_float = 99999.56968
num_str = str(num_float)
print("num_str: ", num_str)
print("Type of num_float: ", type(num_float))
print("Type of num_str: ", type(num_str))

Output:

num_str:  99999.56968
Type of num_float:  <class 'float'>
Type of num_str:  <class 'str'>

📌 Method 2: Using String formatting – format() | f-string | %s

  • The format() method formats the specified value(s) and inserts them inside the string’s placeholder. Curly brackets ‘{} ’ are used to define the placeholder.
  • f-string is used as f’{float}’, where value inside curly bracket will help to convert the float into string.
  • “%s”%float, helps to convert the given integer to string by adding a value into Python string.

Example:

val_float = 20.19  # floating-point value
print("type of val_float: ", type(val_float))

# Using format()
val_str1 = "Year: {}".format(val_float)
print("type of val_str1: ", type(val_str1))

# Using f-string
val_str2 = f"{val_float}"
print("type of val_str2: ", type(val_str2))

# Using %s
val_str3 = '%s' % val_float
print("type of val_str3: ", type(val_str3))

Output:

type of val_float:  <class 'float'>
type of val_str1:  <class 'str'>
type of val_str2:  <class 'str'>
type of val_str3:  <class 'str'>

Conclusion

I hope this article helped you to understand how to convert a string object into a float object and vice-versa. Please stay tuned and subscribe for more exciting articles. Happy coding.

Recommended Tutorial: How to Convert a String List to a Float List in Python?


The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!