2

I am quite confused with the soultions for removing decimal precision using python.

For instance, I have the following number:

9.1234567891235 --> float.

I want to only 9 digits of number after decimal point. Not rounding.

And the end result also should be float.

I have gone through some solutions. but to hit this directly.

Just guide me to function that I can use.

Thanks

  • If you do not want to round. How about converting it to string and strip the rest of the decimals. There is a nice library in Python for safely handing decimals https://docs.python.org/3/library/decimal.html#module-decimal – mad_ Jun 09 '20 at 16:11
  • I think this post may be useful: https://stackoverflow.com/questions/8595973/truncate-to-three-decimals-in-python – Asriel Jun 09 '20 at 16:18

2 Answers2

3

Does this work for you:

num = 9.1234567891235
print(float("%.9f" % num))
# 9.123456789
panadestein
  • 1,061
  • 8
  • 18
  • A small additing here, the environment i am in is Jython. So I am getting an following error TypeError: float argument required, not java.math.BigDecimal Any idea on this – Arun Sunderraj Jun 09 '20 at 18:03
  • @ArunSunderraj it works for me in Jython 2.7. You can also [Try it online!](https://tio.run/##K6gsycjPM9LNAtP//@eV5irYKljqGRoZm5iamVtYAhmmXAVFmXklGmk5@YklGkqqepZpSgqqCkClmpr//wMA "Python 2 (Jython) – Try It Online") – panadestein Jun 09 '20 at 19:06
1
a= 9.1234567891235

def round_down(a, decimals):
    return round(a - 0.5 * 10**(-decimals), decimals)

round_down(a, decimals=9)
9.123456789
warped
  • 6,239
  • 3
  • 16
  • 35