Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - convert string into a number

I'm working with python and django, and i have this problem: I have different variables storing the price of a object, all of them in a format like 350.32, 182.40, etc...

My problem is that these numbers are strings, but in my function i have to sum them to reach a total, and python won't let me do it because it can't sum strings. I've tried int(), float(), format(), and Decimal(), but they give me always a value with only one decimal number or other incorrect values. I need 2 decimal numbers and I need the possibility to sum them all. How can i do it?

PS: sorry for any english mistakes, i'm italian.

like image 245
Simone Avatar asked Mar 15 '23 09:03

Simone


2 Answers

Decimal seems to work for me.

If these are prices, do not store them as floats ... floats will not give you exact numbers for decimal amounts like prices.

>>> from decimal import Decimal
>>> a = Decimal('1.23')
>>> b = Decimal('4.56')
>>> c = a + b
>>> c
Decimal('5.79')
like image 58
reteptilian Avatar answered Mar 24 '23 10:03

reteptilian


I'm using Python 3.4.0, and this works for me:

>>>a = '350.32'
>>>float(a)
350.32

To round it to 2 decimal places, do this:

>>>b = '53.4564564'
>>>round(float(b), 2)
53.46
like image 34
SilentDev Avatar answered Mar 24 '23 09:03

SilentDev