summaryrefslogtreecommitdiffstats
path: root/Lib/_pydecimal.py
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2024-10-14 08:24:01 (GMT)
committerGitHub <noreply@github.com>2024-10-14 08:24:01 (GMT)
commit5217328f93f599755bd70418952392c54f705a71 (patch)
tree87e238d2b2cdd326b396db73e582c535ef623836 /Lib/_pydecimal.py
parent4b358ee647809019813f106eb901f466a3846d98 (diff)
downloadcpython-5217328f93f599755bd70418952392c54f705a71.zip
cpython-5217328f93f599755bd70418952392c54f705a71.tar.gz
cpython-5217328f93f599755bd70418952392c54f705a71.tar.bz2
gh-121798: Add class method Decimal.from_number() (GH-121801)
It is an alternate constructor which only accepts a single numeric argument. Unlike to Decimal.from_float() it accepts also Decimal. Unlike to the standard constructor, it does not accept strings and tuples.
Diffstat (limited to 'Lib/_pydecimal.py')
-rw-r--r--Lib/_pydecimal.py15
1 files changed, 15 insertions, 0 deletions
diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py
index 75df3db..5b60570 100644
--- a/Lib/_pydecimal.py
+++ b/Lib/_pydecimal.py
@@ -583,6 +583,21 @@ class Decimal(object):
raise TypeError("Cannot convert %r to Decimal" % value)
@classmethod
+ def from_number(cls, number):
+ """Converts a real number to a decimal number, exactly.
+
+ >>> Decimal.from_number(314) # int
+ Decimal('314')
+ >>> Decimal.from_number(0.1) # float
+ Decimal('0.1000000000000000055511151231257827021181583404541015625')
+ >>> Decimal.from_number(Decimal('3.14')) # another decimal instance
+ Decimal('3.14')
+ """
+ if isinstance(number, (int, Decimal, float)):
+ return cls(number)
+ raise TypeError("Cannot convert %r to Decimal" % number)
+
+ @classmethod
def from_float(cls, f):
"""Converts a float to a decimal number, exactly.