FloatSafeDecimal
A subclass of the Decimal type which can handle floating point values gracefully by converting them to strings before trying to convert them to Decimals.
To see why this is valuable, consider the following python shell session where we construct Decimal values from floats and strings in turn:
initial_val = 20.6
Decimal(initial_val) Decimal('20.60000000000000142108547152020037174224853515625')
Decimal(str(initial_val)) Decimal('20.6')
- NOTE ON EDGE CASES FOR HIGH PRECISION INPUTS *
Note that cpython itself only retains up to 17 digits of precision for a float, and disregards the rest, so if your input is a really big float, then this won't do you much good, because:
str(float('1.11111111111111111111111111111111111111111111111')) '1.1111111111111112'
- whereas
str(Decimal('1.11111111111111111111111111111111111111111111111')) '1.11111111111111111111111111111111111111111111111'
But that's not really the problem this class is trying to help with. It's to help with what look like 'simple' numbers (like 20.2), which end up being converted to very long ones with a slightly different value when converted to a decimal.
Example
619.38