user3533755
user3533755

Reputation: 191

Format list of tuples to 1 decimal

How would I format a number to always have 1 decimal place? I have 4 numbers I want to add to a tuple, each having exactly 1 decimal place. I tried messing around with .format but couldn't seem to get it to work with a tuple.

a = 1
b = 2
c = 3
d = 4.44
my_tup = (a,b,c,d)

And I want my_tup to be formatted like so. (1.0, 2.0, 3.0, 4,4)

Thanks for the help!

Upvotes: 1

Views: 5010

Answers (3)

Adam Smith
Adam Smith

Reputation: 54213

decimal is the proper solution, since these are decimal numbers not floating point.

import decimal

a, b, c, d = 1, 2, 3, 4.44
my_tup = tuple(map(decimal.Decimal, map("{:.1f}".format, [a,b,c,d])))

This is basically just:

a, b, c, d = 1, 2, 3, 4.44

# strip the nonsignificant digits
a = "{:.1f}".format(a) # 1.0
b = "{:.1f}".format(b) # 2.0
c = "{:.1f}".format(c) # 3.0
d = "{:.1f}".format(d) # 4.4

my_tup = (decimal.Decimal(a), decimal.Decimal(b),
          decimal.Decimal(c), decimal.Decimal(d))

Upvotes: 0

Lorenzo
Lorenzo

Reputation: 433

If you are only want to see the numbers with one decimal place visually, but preserve the accuracy, use the string formatting:

print "%.1f" % number

If you want to round the number: math.round(number,1)

math.floor and math.ceil will allow to round strictly down or up

Upvotes: 1

s16h
s16h

Reputation: 4855

a, b, c, d = 1, 2, 3, 4.44
my_tup = (a, b, c, d)
my_tup = tuple([float("{0:.1f}".format(n)) for n in my_tup])

However, tuple is an immutable sequence so you can't change it after you have created it. It's probably better to have your numbers formatted correctly before you put them in a tuple; this will also avoid the whole (ugly) create a list then create a tuple from it in tuple([float("{0:.1f}".format(n)) for n in my_tup])

Upvotes: 6

Related Questions