0

I have the following code:

print ("Cost: %f per %s" % (mrate[choice], munit[choice]))

Output:

Cost: 25.770000 per 10gm tube

How can I get it to round to two decimals while printing, so that I get 25.77 in the output?

Joel G Mathew
  • 6,611
  • 14
  • 47
  • 76

4 Answers4

2
>>> print ("Cost: %f" % 25.77)
Cost: 25.770000
>>> print ("Cost: %.2f" % 25.77)
Cost: 25.77

Unsure where to find it exactly in PyDoc, but at least the same width-precision rules can be found here.

bipll
  • 11,563
  • 1
  • 17
  • 33
1

If you use %.2f you will get 2 decimal places for you float like:

Test Code:

value = 25.7700000001
print("%f %.2f" % (value, value))

Results:

25.770000 25.77
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
1

use round function to restrict decimal places.

print ("Cost: %.2f per %s" % (round(mrate[choice],2), munit[choice]))

Or replace "%f" with "%.2f"

Randeep Singh
  • 81
  • 1
  • 1
  • 10
1

You need to use format specifications in your print function like this:

value = 25.7700000001
print("%.2f" % (value))
Taohidul Islam
  • 5,008
  • 3
  • 23
  • 37