0

I am working on a python project and get a problem.

I have a for loop that makes a list with numbers. The problem is when I print out the list to check if the numbers are correct.

Some of the more simpler calculations are: 2.6 * 3 and 1.3 * 9

If you check with a calculator you should get 7.8 and 11.7, but I get 7.800000000000001 and 11.700000000000001

Which is not a big problem, but I don't like how it looks. (First world problem, I know)

Is there any way to fix it?

user3685412
  • 4,057
  • 3
  • 16
  • 16
  • These are not "trailing numbers" - the numbers you are working with are not sums of exact powers of two. – doctorlove Jun 23 '14 at 10:35
  • If you are using numpy, you can use `numpy.set_printoptions(precision=N)` to round the output to N digits. This only affects the displaying of the numbers, not the actual value and works only with arrays, not lists or single numbers – DenDenDo Jun 23 '14 at 11:16

4 Answers4

1

Use string format?

print "%.2f" % (2.6 * 3)

The %.2f means print a float to 2dp

Holloway
  • 6,412
  • 1
  • 26
  • 33
0

You can use format to display the output you want:

>>> print(format(2.6 * 3, ".1f"))
7.8

Here ".1f" means "floating point number to one decimal place".

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

You can use format print.

res = 2.6*3
"%0.2f" % res
Jimilian
  • 3,859
  • 30
  • 33
0

Here's a complete example with a list.

 >>> n = [1.9, 7.8 , 9,3.4]
 >>> print n
      [1.8999999999999999, 7.7999999999999998, 9, 3.3999999999999999]
 >>> twodecimals = ["%.2f" % v for v in n]
 >>> print twodecimals
      ['1.90', '7.80', '9.00', '3.40']
  >>> print twodecimals[0]
      1.90

%.2f means prints only 2 decimal points. Similarly, .1f means 1 decimal point and so on.

user2481422
  • 868
  • 3
  • 17
  • 31