[Python-ideas] Python Float Update

drekin at gmail.com drekin at gmail.com
Wed Jun 3 16:44:06 CEST 2015


Andrew Barnert wrote:

>> Oh, another thought... Decimals could gain yet another conversion 
>> method, one which implicitly uses the float repr, but signals if it was 
>> an inexact conversion or not. Explicitly calling repr can never signal, 
>> since the conversion occurs outside of the Decimal constructor and 
>> Decimal sees only the string:
>> 
>> Decimal(repr(1.3)) cannot signal Inexact.
>> 
>> But:
>> 
>> Decimal.from_nearest_float(1.5)  # exact
>> Decimal.from_nearest_float(1.3)  # signals Inexact
>> 
>> That might be useful, but probably not to beginners.
> 
> I think this might be worth having whether the default constructor is changed or not.
> 
> I can't think of too many programs where I'm pretty sure I have an exactly-representable decimal as a float but want to check to be sure... but for interactive use in IPython (especially when I'm specifically trying to explain to someone why just using Decimal instead of float will/will not solve their problem) I could see using it.

How about more general Decimal.from_exact that does the same for argument of any type – float, int, Decimal object with possibly different precission, fraction, string. Just convert the argument to Decimal and signal if it cannot be done losslessly. The same constructor with the same semantics could be added to int, float, Fraction as well.

Regards, Drekin



More information about the Python-ideas mailing list