Python - How To Convert String to Decimal in Python

ID : 41

viewed : 197

Tags : PythonPython StringPython Float

vote vote

95

Strings in Python can take numeric values. Similar to other popular programming languages, Python supports Integer and Floating-point (or decimal) numbers and has separate data types assigned for them. Sometimes, there is a need for converting the numeric values taken in a string to an integer or a floating-point number.

This tutorial will introduce how to convert a string to a decimal in Python.

Use the float() Function to Convert a String to Decimal in Python

Python provides an in-built function called float() that is utilized to transform a string or an integer to a floating-point value.

Here, we will enter a string and perform the float() function on the given string.

The following code uses the float() function to convert a string to decimal in Python.

a = '5.54' x = float(a) print(x) 

The above code provides the following output:

5.54 

Use Exception Handling Convert a String Containing a Comma to a String in Python

When a comma separates the numbers in the string and the float() function is directly called on the string, then it gives a ValueError.

The following example code will help you understand it better.

a = "1,5.54" x = float(a) print(x) 

The above code provides the following output:

Traceback (most recent call last):   File "<string>", line 2, in <module> ValueError: could not convert string to float: '1,5.54' 

We can take a quick detour from the original code and use exception handling in this code to avoid this.

The try...except statement is utilized for the purpose of exception handling in Python. The try...except statement is divided into three blocks; all three of the blocks have a different purpose.

  • The try block contains the cluster of code to be tested for any errors.
  • The except block is used to add exceptions and handle the errors of the code.
  • The finally block contains the statements that need to be executed and is ignored by the try and except blocks.

The following code utilizes exception handling on the original code given above to convert a string to decimal in Python.

a = "1,5.54" try:     x = float(a) except ValueError:     print("Invalid Float number to be converted. ") 

The above code provides the following output:

Invalid Float number to be converted. 

Use String Formatting Along With the float() Function to Convert a String to Decimal in Python

In a given string, if we want to specify the number of decimal points that we want to have in the floating-point variable, then we can use string formatting along with the in-built float() function.

The following code uses string formatting to convert a string to decimal in Python.

a = "5.54231" x = float(a) x = "{:.2f}".format(x) print(x) 

The above code provides the following output:

5.54 

Use List Comprehension to Convert a List of Strings to Float in Python

List comprehension is a relatively shorter and very graceful way to create lists that are to be formed based on given values of an already existing list.

We can use list comprehension and convert all the values within the list to floating-point values using the float() method in the list comprehension.

The following code uses list comprehension to convert a list of strings to float in Python.

lst= [ '1.22', '5.54', '6.858'] x = [float(i) for i in lst] print(x) 

The above code provides the following output.

[1.22, 5.54, 6.858] 

Use numpy.float() Function to Convert a String to Decimal in Python

The term NumPy is an acronym for Numerical Python. This library makes the use of arrays possible in Python. It also provides functions that help in manipulating these arrays.

The numpy.float() function works similarly to the in-built float() function in Python, with the only difference being that the numpy.float() function is made to work with arrays. It always generates an array of floating-point values.

The following code uses the numpy.float() function to convert a string to decimal in Python.

import numpy as np lst= [ '1.22', '5.54', '6.858'] print(list(np.float_(lst))) 

The above code provides the following output:

[1.22, 5.54, 6.858] 

Use the astype() Method From the NumPy Library to Convert a String to Decimal in Python

The NumPy library contains an in-built astype() method that assists in converting the data type of the given NumPy array.

The following code uses the astype() method from the NumPy library to convert a string to decimal in Python.

import numpy as np a = np.array(["1.22", "5.54", "6.858"]) x = a.astype(float) print(x) 

The above code provides the following output:

[1.22  5.54  6.858] 

Use the decimal Module to Convert a String to Decimal in Python

The decimal module supplies functions that perform faster operations than the stock floating-point functions.

The decimal.Decimal() function, which is a constructor, takes input as a numeric value and carries out the process to convert it to a decimal type, which is ideal for storing and representing the numeric values meanwhile strictly preserving the precision of the number.

The following code uses the decimal module to convert a string to decimal in Python.

from decimal import Decimal a = '5.54262' x = Decimal(a) print(x) 

The above code provides the following output:

5.54262 

  • Related HOW TO?