Reputation: 21
Hi I need some help please. I want to calculate float numbers with a format like xxxxx.yyyyyyyyyyyyyyy. I have learned that I should use Decimal instead of float I tried a lot, and I searched a lot but I still have the following simple problem:
getcontext().prec = 14
a = Decimal(str('12.737791301'))
b = Decimal(str('12.737791839'))
c = Decimal((b - a)) # substract is what I finally want here
print a, b, c
12.737791301 12.737791839 5.38E-7
I want c to be displayed as 0.000000538
thanks for your help!
ps. normalize() did not work
Upvotes: 2
Views: 514
Reputation: 26040
You may use quantize
. Something along the lines of
c_dec = Decimal(c)
NUMPLACES = Decimal(10)**( c_dec.adjusted() -3)
c_str = str( c_dec.quantize(NUMPLACES) )
print c_str
EDIT. In your particular example the following works:
#!/usr/bin/python
import decimal as dec
a = dec.Decimal(str('12.737791301'))
b = dec.Decimal(str('12.737791839'))
c = dec.Decimal((b - a)) # substract is what I finally want here
print a
print b
sign, digits, exponent=c.as_tuple()
ld=list(digits)
PREC=14
for i in range(0,exponent+PREC+1):
ld.insert(0,0)
cstr="0."
for d in ld:
cstr+=str(d)
print cstr
If you want something more robust, look up this example http://docs.python.org/library/decimal.html#recipes
Upvotes: 0
Reputation: 31130
The real solution is format(), available in python 2.6 and 3.1.
format(c,"f")
will convert the decimal to float repr-style output. This is part of the new style formatting in python.
Other worse ideas for solutions are below:
This can be accomplished with a format string, as if your Decimal values were floats.
print "%0.9f" % c
will produce '0.000000538'
The python library reference can tell you more.
To get around the problem of needing to know the right number of decimal places, you could always print it out at the limit of float precision with a condition in case the Decimal is smaller:
out = "%.16f" % c if c >= 1e-16 else "0.0"
print out.rstrip('0')
With the second line dealing with the trailing 0s.
Upvotes: 5