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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With