1

I have a variable mn whose value is 2.71989011072, I use round function of python to get a precision value of 2.720 but I get 2.72 only

mn=2.71989011072
print round(mn,3)

Gives 2.72 and not 2.720

talonmies
  • 70,661
  • 34
  • 192
  • 269
D14TEN
  • 337
  • 6
  • 15

4 Answers4

3

Yes, the print function apply a second rounding.

mn = 2.71989011072
mn = round(mn, 3)
print(mn)

You'll get:

2.72

You need to use a formatted string:

print("{0:.3f}".format(mn))

You'll get:

2.720

Notice that the formatted string can do the rounding for you. With this, you'll get the same output:

mn = 2.71989011072
print("{0:.3f}".format(mn))
# => 2.720
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
1

Function rounds it to three first digits which correctly results in 2.72. The zeros are matter of printing ans string formatting, not rounding.

To print it with three zeros you will need to do the following:

print '{0:.3f}'.format(round(mn, 3))

That will round number first and then print it, formatting it with three zeros.

Dmitry Torba
  • 3,004
  • 1
  • 14
  • 24
1

You desire a particular string representation of the number, not another number.

Use format() instead of round():

>>> mn = 2.71989011072
>>> format(mn, '.3f')
'2.720'
akashnil
  • 253
  • 2
  • 10
0

with python 3, we can use f strings

print(f"{mn:.3f}")

2.720

Venkatachalam
  • 16,288
  • 9
  • 49
  • 77