Python: Converting string into decimal number

201,972

Solution 1

If you want the result as the nearest binary floating point number use float:

result = [float(x.strip(' "')) for x in A1]

If you want the result stored exactly use Decimal instead of float:

from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]

Solution 2

If you are converting price (in string) to decimal price then....

from decimal import Decimal

price = "14000,45"
price_in_decimal = Decimal(price.replace(',','.'))

No need for the replace if your strings already use dots as a decimal separator

Solution 3

You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]

Solution 4

use the built in float() function in a list comprehension.

A2 = [float(v.replace('"','').strip()) for v in A1]

Solution 5

A2 = [float(x.strip('"')) for x in A1] works, @Jake , but there are unnecessary 0s

Share:
201,972
Admin
Author by

Admin

Updated on July 08, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a python list with strings in this format:

    A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
    

    How do I convert those strings into decimal numbers to perform arithmetic operations on the list elements?

  • Jake
    Jake over 13 years
    Tested this and realised it does not work because the strings have whitespace and extra quote marks in them.
  • DSM
    DSM over 13 years
    You need to strip the extra space as well.
  • Mark Tolonen
    Mark Tolonen over 13 years
    Tested with a cut-and-paste of the OP's example? It didn't work as is.
  • Mark Tolonen
    Mark Tolonen over 13 years
    Does not work with OP's exact example. Zeroes aren't "unnecessary". float can't represent all decimals exactly in binary. But see Mark Byers answer.
  • Jake
    Jake over 13 years
    @Mark, I've no idea what I did differently yesterday but it's not working now. Perhaps the question has been edited since I copied it.
  • tehfink
    tehfink over 5 years
    Doesn't this method lose the last 2 decimal places, resulting in a larger number?
  • freerunner
    freerunner over 5 years
    price_in_decimal = Decimal(price.replace(',','.')) This is what @Nids intended I suppose. Replacing the , with .
  • Victor
    Victor about 4 years
    @freerunner exactly!