On 1/21/2020 11:52 AM, Steven D'Aprano wrote:
I don't really care whether there's documentation for __str__() or __repr__() or something else. I'm just thinking that there should be some way to guarantee a well defined "useful" float output formatting. https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatti...
https://docs.python.org/3/library/string.html#format-string-syntax Thanks. For some reason nobody in #python pointed me to the 'g' format type. That resolves my issue.
Unfortunately, because 'g' can strip the trailing ".0" floats formatted with it no longer satisfy the float->str->float immutability property. I don't see why. Any string you get back from %g ought to convert back to a float without loss of precision, the trailing '.0' should not affect it. Can you give an example where it does?
It seems to work for me.
py> x = 94.0 py> float('%g' % x) == x True
The reason repr adds the '.0' that 'g' does not is to avoid this problem:
type(eval(repr(17.0))) == type(17.0) True type(eval(format(17.0, '.17g'))) == type(17.0) False
Eric