Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Converting string into decimal number

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?

like image 436
Sankar A Avatar asked Jan 10 '11 05:01

Sankar A


People also ask

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 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") .

Can string be converted to integer in Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer. But use of the int() function is not the only way to do so.

How do you cast a decimal number in Python?

If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))


1 Answers

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] 
like image 68
Mark Byers Avatar answered Oct 17 '22 22:10

Mark Byers