1

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
2
  • thanks, but its slightly more complex in that i want to create a new array that contains the rounded numbers, im at a bit of a loss of how to do that without a counter, which is usually how i do it Commented Nov 27, 2009 at 3:38
  • Your while condition should check L1[count], not just L1. The truth value of L1 never changes. Commented Nov 27, 2009 at 10:16

4 Answers 4

9

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0
L2=["%.2f" %i for i in L1]

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.