How to Convert String to Float in Python

2 ways to convert a string to float in Python:

  1. Using float() Method
  2. Using numpy.float64() Method

Method 1: Using float() Method

Example 1: Basic Usage

Visual Representation of Using float() Method

# String representation of a floating-point number
string_value = "21.53436"

print("======= Before conversion =======")
print(string_value)
print(type(string_value))

# Convert string to float
float_value = float(string_value)

print("======= After conversion =======")
print(float_value )
print(type(float_value ))

Output

======= Before conversion =======
21.53436
<class 'str'>
======= After conversion =======
21.53436
<class 'float'>

Example 2: Formatting a Floating-Point Number to Two Decimal Places

string_value = "21.53436"

float_value = float(string_value)

formatted_float_value = "{:.2f}".format(float_value) 

print("======= After conversion =======")
float_value = float(formatted_float_value)

print(float_value)
print(type(float_value))

Output

21.53
<class 'float'>

Example 3: ValueError: could not convert string to float

string_value = "21.53aw6"

float_value = float(string_value)

print("======= After conversion =======")
print(float_value )
print(type(float_value ))

Output

ValueError: could not convert string to float: '21.53aw6'

Above code raises a ValueError because the string does not represent a valid floating-point number.

To prevent such errors, implement exception handling to catch ValueError exceptions.

string_value = "21.53aw6"

try:
 float_value = float(string_value)
 print("======= After conversion =======")
 print(float_value)
 print(type(float_value))
except ValueError:
 print("The string does not represent a valid floating-point number.")

Output

The string does not represent a valid floating-point number.

Method 2: Using numpy.float64() Method

Visual Representation of Using numpy.float64() Method

import numpy as np 

string_value = "21.53436"
print("======= Before conversion =======")
print(string_value)
print(type(string_value))

float_value = np.float64(string_value)

print("======= After conversion =======")
print(float_value )
print(type(float_value ))

Output

======= Before conversion =======
21.53436
<class 'str'>
======= After conversion =======
21.53436
<class 'numpy.float64'>

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.