views:

407

answers:

5

my L1 array contains numbers like 0.029999999999999999 which i want to print off as 0.03

my code works, but gives an error at the end because the last count is out of range. i understand why it breaks, but dont know how to fix it. thanks

count = 1

while L1:
    print "%.2f" %L1[count]
    count = count + 1
+9  A: 

If you want to print all numbers in L1, use:

for x in L1: print '%.2f' % x

If you want to skip the first one, for x in L1[1:]: will work.

Edit: the OP mentions in a comment (!) that their desire is actually to "create a new array" (I imagine they actually mean "a new list", not an array.array, but that wouldn't be very different). There are no "rounded numbers" in the float world -- you can use round(x, 2), but that will still give you a float, so it won't necessarily have "exactly 2 digits". Anyway, for a list of strings:

newlistofstrings = ['%.2f' % x for x in L1]

or for one with decimal numbers (which can have exactly 2 digits, if you want):

import decimal
newlistofnnumbers = [decimal.Decimal('%.2f') % x for x in L1]
Alex Martelli
+2  A: 

Why don't you just loop through the L1 list instead of doing a while loop?

for i in L1:
   print "%.2f" % i

Keep it simple :)

Bartek
A: 

cool, i was missing a simple concept (just remebering python)

for i in L1:
    b="%.2f" % i
    L2.append(b)

gives me a new array with my wanted values, thanks again for both your help

amuk
A: 
L2=["%.2f" %i for i in L1]
inspectorG4dget
A: 

2 problems:

  1. Your loop never ends (while L1)
  2. You start indexing with 1 (count = 1 in initialisation)

Better is, like the others said:

for i in L1:
    print "%.2f" % i

and if you also need the index (count):

for (index, item) in enumerate(L1):
    print "Element number (0-based) %d is %f" % (index, item)

See also Pythonic expressions for some more nice ways to use python.

extraneon