3 ms·
I still would prefer floats as default instead of decimals. What should be fixed is how you have to convert a float to a string to then convert it to a decimal.
by Sephr 17y ago
I still would prefer floats as default instead of decimals. What should be fixed is how you have to convert a float to a string to then convert it to a decimal.
- jerf 17y agoPython is trying to tell you something. By the time you've got a float, it's too late to turn it into a Decimal. The operation doesn't make sense. You can argue about the details, but a floating point number doesn't represent a number, it represents a numeric range, the exemplar of an infinite set of values that would map to the same float if converted to a float. When you ask to turn a float into a Decimal, which element of the range the float represents are you trying to turn into an exact Decimal? The operation is ill-defined. All hacking it up with a string does is convince Python that you actually mean that exact number, but you're hacking. Either convert where you got that "float" directly into Decimal (where Python can't tell enough to know where the number came from), or deal with the fact that you are cheating and it may bite you in the future. So, no, the correct solution is not to "convert the input into a float, then convert that into a string, then convert that to a Decimal"; the correct solution is to make sure you never pass through float in the first place. Unless you're loading a binary file specified as containing IEEE-754 floats, you probably didn't actually have to cut through the float stage. Anything other than the correct solution should be expected to be annoying and blow up at random times. Floats are treacherous little bastards, and all attempts to paper over that fact will lead to grief.