Convert string to decimal python

There are two floating-point data types. Float and Decimal. It depends on your program demand which one you want to use. Decimal provides a high level of accuracy and it's more precise than Float.

To convert a value string to float just do it:

num = "29.0"
print (float(num))

To convert string to decimal

from decimal import Decimal
num = "29.0"
print (Decimal(num))

For your specific question, you can use the below code. Both are working for me.

from decimal import Decimal
import re

result = [float(x.strip(' "')) for x in A1]
print(result)
#[29.0, 65.2, 75.2]


result = [Decimal(x.strip(' "')) for x in A1]
print(result)
#[Decimal('29.0'), Decimal('65.2'), Decimal('75.2')]


result = [float(re.search(r'\d+.\d+',number).group()) for number in A1]
print(result)
#[29.0, 65.2, 75.2]

result = [Decimal(re.search(r'\d+.\d+',number).group()) for number in A1]
print(result)
#[Decimal('29.0'), Decimal('65.2'), Decimal('75.2')]

  1. Use the float() Function to Convert a String to Decimal in Python
  2. Use Exception Handling Convert a String Containing a Comma to a String in Python
  3. Use String Formatting Along With the float() Function to Convert a String to Decimal in Python
  4. Use List Comprehension to Convert a List of Strings to Float in Python
  5. Use numpy.float() Function to Convert a String to Decimal in Python
  6. Use the astype() Method From the NumPy Library to Convert a String to Decimal in Python
  7. Use the decimal Module to Convert a String to Decimal in Python

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 "", line 2, in 
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 Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python

    Related Article - Python Float

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • How do you change string to decimal?

    Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.

    How do you convert a string to a decimal with two decimal places in Python?

    Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

    How do I convert a string to a number in Python?

    To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

    What is decimal () in Python?

    In Python, there is a module called Decimal, which is used to do some decimal floating point related tasks. This module provides correctly-rounded floating point arithmetic. To use it at first we need to import it the Decimal standard library module. import decimal.