[Tutor] How to convert a long decimal into a string?
Dick Moores
rdm at rcblue.com
Tue Jan 16 20:53:22 CET 2007
Here's a function I wrote some time ago, and just discovered that in
one important category of cases, long numbers with a decimal point,
it doesn't do what I intended.
=====================================================
def numberRounding(n, significantDigits=4):
"""
Rounds a number (float or integer, negative or positive) to any number of
significant digits. If an integer, there is no limitation on it's size.
"""
import decimal
def d(x):
return decimal.Decimal(str(x))
decimal.getcontext().prec = significantDigits
return d(n)/1
======================================================
Now, print
numberRounding(232.3452345230987987098709879087098709870987098745234,
30) prints
232.345234523
whereas if the first argument is enclosed in quotes, it does what I
indended. Thus:
print
numberRounding('232.3452345230987987098709879087098709870987098745234',
30) prints
232.345234523098798709870987909 .
So my question is, how can I revise numberRounding() so that it is
not necessary to employ the quotes. Or alternatively, is there a way
to non-manually put quotes around an argument that is a long decimal?
If have no idea at all about the second. As for the first, I believe
I could devise an algorithm for first converting n to an int (for
example, multiplying the above n by 1000), converting to a string,
putting the decimal point back in between indices 2 and 3, then using
that string as n (thereby avoiding the use of quotes around n as the
first argument). But I have the feeling that Python must have a way
already built in. Does it?
Thanks,
Dick Moores
More information about the Tutor
mailing list