I need to display a number, let's say 0.9 exact at least until 17 decimal places. Even if I use Decimal or mpf, it gives me the result as if I would not be using them at all.
from mpmath import mpf
from decimal import Decimal
from decimal import getcontext
import mpmath
getcontext().prec = 25
mpmath.mp.prec=100
a=mpf("0.9")
b=mpf(0.9)
c=Decimal("0.9")
d=Decimal(0.9)
e=0.9
print("%.17f" % a)
print("%.17f" % b)
print("%.17f" % c)
print("%.17f" % d)
print("%.17f" % e)
The output is
>>0.90000000000000002
>>0.90000000000000002
>>0.90000000000000002
>>0.90000000000000002
>>0.90000000000000002
I have searched everywhere, but I can not seem to find aa solution. Is it even possible to get that precision? What I understood from mpf, they claim a much higher precision than I am getting. What am I missing?
Edited:
I am sorry for a potential misunderstanding, but what I really had in mind, is that I need to perform actual calculations with this number, not only to display it properly.
I suspect that the %
operator converts its argument to a float when using a %f
format. Using f-strings instead (or the .format
method on strings) might be a better idea, since they give the object a better chance of controlling the way it gets formatted.
I just tried this:
Python 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> d=decimal.Decimal('0.1')
>>> '%.20f' % (d,)
'0.10000000000000000555'
>>> f'{d:.20f}'
'0.10000000000000000000'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.