1

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() function rounds the number automatically, but I don't want this. What should I do?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • See related [How to round a floating point number up to certain decimal place?](https://stackoverflow.com/questions/4518641/how-to-round-a-floating-point-number-up-to-certain-decimal-place) for answers that don't have any "edge" cases. – martineau Mar 31 '18 at 22:37
  • Possible duplicate of [Python setting Decimal Place range without rounding?](https://stackoverflow.com/questions/29246455/python-setting-decimal-place-range-without-rounding) – Georgy Apr 27 '18 at 12:44

3 Answers3

0

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**4
print("{:.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.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
  • yes it works. but for lengthy data it costs very much. your answer does 4 extra operation in order to catch the precision while I calculated it in my code. so why I calculate it again? –  Mar 31 '18 at 22:22
  • @Javadmk: If you store the value of `10**4` that will reduce the number of operations. There is a way to do this with string handling, avoiding the multiplication and the division, but that route has some multiple operations and tricky issues of its own and I doubt that it would be significantly faster. My method is short and clear. – Rory Daulton Mar 31 '18 at 22:24
0

Here is one way. truncate function courtesy of @user648852.

from math import sqrt, floor

def truncate(f, n):
    return floor(f * 10 ** n) / 10 ** n

x = sqrt(19) # x : 4.358898943540674

print("{0}".format(truncate(x, 4)))
# 4.3588
jpp
  • 159,742
  • 34
  • 281
  • 339
  • as I said in the previous answer, this is not an efficient way for solving the problem. any better algorithm will be appreciated. –  Mar 31 '18 at 23:34
0

Do more work initially and cut away a fixed number of excess digits:

from math import sqrt

x = sqrt(19) # x : 4.358898943540674

print(("{:.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.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51