How To Prevent Automatic Rounding In Print Function When Printing A Float Number?
Let's consider this situation: from math import sqrt x = sqrt(19) # x : 4.358898943540674 print('{:.4f}'.format(x)) # I don't want to get 4.3589 # I want to get 4.3588 The print
Solution 1:
If you want to round the number down to the 4th decimal place rather than round it to the nearest possibility, you could do the rounding yourself.
x = int(x * 10**4) / 10**4print("{:.4f}".format(x))
This gives you
4.3588
Multiplying and later dividing by 10**4
shifts the number 4 decimal places, and the int
function rounds down to an integer. Combining them all accomplishes what you want. There are some edge cases that will give an unexpected result due to floating point issues, but those will be rare.
Solution 2:
Here is one way. truncate
function courtesy of @user648852.
from math import sqrt, floor
deftruncate(f, n):
return floor(f * 10 ** n) / 10 ** n
x = sqrt(19) # x : 4.358898943540674print("{0}".format(truncate(x, 4)))
# 4.3588
Solution 3:
Do more work initially and cut away a fixed number of excess digits:
from math import sqrt
x = sqrt(19) # x : 4.358898943540674print(("{:.9f}".format(x))[:-5])
gives the desired result. This could still fail if x has the form ?.????999996
or similar, but the density of these numbers is rather small.
Post a Comment for "How To Prevent Automatic Rounding In Print Function When Printing A Float Number?"