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
  • 7,561
  • 15
  • 54
  • 86

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,747
  • 1
  • 18
  • 32
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
  • 47,830
  • 31
  • 106
  • 135
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
  • 91
  • 1
  • 2
  • 11
1

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

value = 25.7700000001
print("%.2f" % (value))
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39