5

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.

Richard Seal
  • 4,248
  • 14
  • 29
Simone
  • 87
  • 1
  • 5
  • If these variables are Django model fields, have you considered to make them [`DecimalField`s](https://docs.djangoproject.com/en/1.8/ref/models/fields/#decimalfield) instead of whatever field type they are now? – das-g Oct 22 '15 at 20:32
  • Problem solved, i used float(number) to be able to sum all the prices and it works fine, then for the 2 decimal places, in my html page i used {{ total_price|floatformat:2 }}. – Simone Oct 23 '15 at 13:18

4 Answers4

7

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')
Community
  • 1
  • 1
reteptilian
  • 903
  • 8
  • 12
  • @Suppose `a='50.13342'`. Is it possible to round this? When I try `>>>from decimal import Decimal` `>>>round(Decimal('123.1231231', 2))` it returns `123.0` for some reason. I am using Python 3.4.0. Even if I try `>>>round(Decimal('123.1231231', 5))` it returns the same thing (`123.0`). – SilentDev Oct 22 '15 at 20:52
  • 2
    @user2719875 Try giving the 2 or 5 to `round` instead of to `Decimal`. – Stefan Pochmann Oct 22 '15 at 21:29
1

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
SilentDev
  • 20,997
  • 28
  • 111
  • 214
  • OP said these are prices. [Storing prices as floats is bad](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) – reteptilian Oct 22 '15 at 20:39
  • @ppperry True. I actually posted this just to show that I am using Python 3.4.0 and the conversion did work for me. – SilentDev Oct 22 '15 at 20:46
0
import re

eggs = "12.4, 15.5, 77.2"

print(sum(map(float, re.split("\s*,\s*", eggs))))
user996142
  • 2,753
  • 3
  • 29
  • 48
0

This give perfect decimal values to five decimal places

import random
from decimal import Decimal  

def myrandom():
    for i in range(10):
        Rand = Decimal(random.random()* (0.909 - 0.101) + 0.101)
        Rand = '{0:0.5f}'.format(Rand)
        print (Rand)

myrandom()
Goulouh Anwar
  • 737
  • 1
  • 11
  • 21