Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
ff1f9730
Commit
ff1f9730
authored
Feb 07, 2008
by
Raymond Hettinger
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
The float conversion recipe is simpler in Py2.6
parent
d0e5b766
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
15 additions
and
25 deletions
+15
-25
Doc/library/decimal.rst
Doc/library/decimal.rst
+15
-25
No files found.
Doc/library/decimal.rst
View file @
ff1f9730
...
...
@@ -1581,31 +1581,21 @@ Q. Is there a way to convert a regular float to a :class:`Decimal`?
A. Yes, all binary floating point numbers can be exactly expressed as a
Decimal. An exact conversion may take more precision than intuition would
suggest, so
trapping :const:`Inexact` will
signal a need for more precision::
suggest, so
we trap :const:`Inexact` to
signal a need for more precision::
def floatToD
ecimal(f):
def float_to_d
ecimal(f):
"Convert a floating point number to a Decimal with no loss of information"
# Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
# exponent. Double the mantissa until it is an integer. Use the integer
# mantissa and exponent to compute an equivalent Decimal. If this cannot
# be done exactly, then retry with more precision.
mantissa, exponent = math.frexp(f)
while mantissa != int(mantissa):
mantissa *= 2.0
exponent -= 1
mantissa = int(mantissa)
oldcontext = getcontext()
setcontext(Context(traps=[Inexact]))
try:
n, d = f.as_integer_ratio()
with localcontext() as ctx:
ctx.traps[Inexact] = True
while True:
try:
return mantissa * Decimal(2) ** exponent
return Decimal(n) / Decimal(d)
except Inexact:
getcontext().prec += 1
finally:
setcontext(oldcontext)
ctx.prec += 1
>>> float_to_decimal(math.pi)
Decimal("3.141592653589793115997963468544185161590576171875")
Q. Why isn't the :func:`floatToDecimal` routine included in the module?
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment