How to Convert String to Float in Python

In this post, I’m going to show you how to convert a string to a float in Python. This is a common task that you might encounter when working with user input, file operations, or data analysis. Let’s get started!

To convert a string to a float in Python, you can use the built-in function float(), which takes a string as an argument and returns a float value.

For example:

num1 = '3.14'
num2 = '2.71'
f1 = float(num1) # this will convert '3.14' to 3.14
f2 = float(num2) # this will convert '2.71' to 2.71
print(f1 + f2) # this will print 5.85

The float() function will raise a ValueError if the string argument is not a valid representation of a float. For example:

num = 'hello'
f = float(num) # this will raise ValueError: could not convert string to float: 'hello'

The float() function will also raise an OverflowError if the string argument is too large or too small to be represented as a float.

For example:

num = '1e1000'
f = float(num) # this will raise OverflowError: (34, 'Result too large')

let’s get into the details:

Why Convert String to Float in Python

A string is a sequence of characters enclosed in quotes. You can use single quotes (”), double quotes (“”), or triple quotes (”’ or “””) to create a string. For example:

name = 'John'
message = "Hello, world!"
quote = """Be the change
that you wish to see in the world."""

A string can contain any character or symbol, including numbers and punctuation. However, Python treats strings as text, not as numbers. That means you can’t perform arithmetic operations on strings, even if they look like numbers. For example:

num1 = '3.14'
num2 = '2.71'
print(num1 + num2) # this will print '3.142.71', not 5.85

A float is a data type that represents a floating-point number, which is a number with a decimal point. For example.

pi = 3.14
e = 2.71
g = 9.81

A float can store very large or very small numbers, up to about 1.8 x 10^308 or 5 x 10^-324. If a number is beyond this range, Python will use the special values ‘inf’ (infinity) or ‘-inf’ (negative infinity) to represent it.

Tips and tricks

Here are some tips and tricks that you can use when converting strings to floats in Python:

  • You can use the format() method or the f-string syntax to format floats with a specified number of decimal places. For example:
pi = 3.14159
print(format(pi, '.2f')) # this will print 3.14
print(f'{pi:.2f}') # this will also print 3.14
  • You can use the split() method to split a string into a list of substrings based on a delimiter, such as a comma or a space. Then you can use the map() function or a list comprehension to apply the float() function to each substring and convert them to floats. For example:
nums = '1,2,3,4,5'
nums_list = nums.split(',') # this will split the string by comma and return ['1', '2', '3', '4', '5']
nums_float = list(map(float, nums_list)) # this will apply the float() function to each element of the list and return [1.0, 2.0, 3.0, 4.0, 5.0]

# alternatively, you can use a list comprehension
nums_float = [float(x) for x in nums_list] # this will do the same thing as above
  • You can use the numpy library to convert strings to floats using the numpy.float64() function, which returns a numpy.float64 object that is compatible with numpy arrays and operations. For example:
import numpy as np
num = '3.14'
f = np.float64(num) # this will convert '3.14' to 3.14 as a numpy.float64 object
print(type(f)) # this will print
print(f + np.pi) # this will print 6.283185307179586

That’s it for this post! I hope you learned something useful about how to convert strings to floats in Python. If you have any questions or feedback, feel free to leave a comment below. Thanks for reading!

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *