3 ms·
Floats can absolutely be formatted, but the result may be unexpected, because it is basically a (hardware based) C binary float: https://en.wikipedia.org/wiki/
by webmaven 10y ago
Floats can absolutely be formatted, but the result may be unexpected, because it is basically a (hardware based) C binary float:
https://en.wikipedia.org/wiki/IEEE_floating_point https://en.wikipedia.org/wiki/IEEE_floating_point
So, because users will typically be surprised that 2.2 + 3.1 results in 5.300000000000001, or that round(2.675, 2) gives 2.67 (instead of 2.68), best practice is to use Decimal, which will give users the results they expect:
https://docs.python.org/3/library/decimal.html https://docs.python.org/3/library/decimal.html
- vosper 10y agoMakes sense. I guess what I was getting at is that introducing Decimal to the example about f-string interpolation makes the example more complicated than it absolutely needs to be, but I can see why they did it.
- webmaven 10y agoI think some of that extra complexity could be papered over with either making decimal() available like int() and float(), which would eliminate the import, and/or implementing a decimal literal format, such as 0d2.675, analogous to the format of Hexadecimal and Octal literals (0xCC00CC and 0o267, respectively).
- mixmastamyk 10y agoI like that second idea, perhaps a mention on the python-ideas mailing list?
- webmaven 10y agoPerhaps. I need to mull it over a bit before I take that plunge (but thank you for the encouragement!). One possible objection is that while Decimal is in the standard library, it isn't a built-in type, so either Decimals need to be elevated to built-ins, or some magic needs to happen when importing the decimal module to add the literal.
- renzon 10y agoThey used Decimal just to show the nested attribute access