D14TEN
D14TEN

Reputation: 289

Floating point numbers precision in python

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

Upvotes: 1

Views: 3600

Answers (4)

Venkatachalam
Venkatachalam

Reputation: 16966

with python 3, we can use f strings

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

2.720

Upvotes: 0

Dmitry Torba
Dmitry Torba

Reputation: 3214

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.

Upvotes: 1

akashnil
akashnil

Reputation: 263

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'

Upvotes: 1

Laurent LAPORTE
Laurent LAPORTE

Reputation: 23002

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

Upvotes: 3

Related Questions