Simone
Simone

Reputation: 97

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.

Upvotes: 5

Views: 8416

Answers (4)

Goulouh Anwar
Goulouh Anwar

Reputation: 767

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()

Upvotes: 0

SilentDev
SilentDev

Reputation: 22747

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

Upvotes: 1

reteptilian
reteptilian

Reputation: 923

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')

Upvotes: 7

user996142
user996142

Reputation: 2883

import re

eggs = "12.4, 15.5, 77.2"

print(sum(map(float, re.split("\s*,\s*", eggs))))

Upvotes: 0

Related Questions