This seems like a really stupid question, but I was honestly not able to find a satisfactory solution. All the "obvious" solutions I've found so far have some hidden problems.
I would like to format floating point values either to an arbitrary width or relative precision, while keeping the adaptive formatting of the {:g} formatting specifier. (Use scientific or normal notation, depending on the magnitude of the number)
Given:
import math # Here is how the default (str) formatting displays these values
# Small values
long_small = 10**-16/3 # 3.3333333333333335e-17
short_small = 10**-16 # 1e-16
# Medium values
long_medium = math.pi # 3.141592653589793
short_medium = 130.0 # 130.0
# Large values
long_large = 10.0**16 + 2 # 1.0000000000000002e+16
short_large = 10.0**16 # 1e+16
In the arbitrary width case, I would like to format these numbers as following (for example, width=8):
long_small # 3.33e-17
short_small # 1.00e-16
long_medium # 3.141593
short_medium # 130.0000
long_large # 1.00e+16
short_large # 1.00e+16
In the arbitrary relative precision case, I would like to format these numbers as following (precision=8):
long_small # 3.33333333e-17
short_small # 1.00000000e-16
long_medium # 3.14159265
short_medium # 130.000000
long_large # 1.00000000e+16
short_large # 1.00000000e+16
{:N.Mf}isn't good enough, because I would like to keep the scientific notation formatting for very large and small numbers{:N.Mg}and{:N.M}aren't good enough, because they discard trailing zeros, also the "width" specifier pads with spaces, instead of adding digits{:N.Me}always uses the scientific notation- any "clever hack", that uses
>0or<0doesn't work, because it either adds leading zeroes, or adds zeroes after the mantissa - any "clever hack", that attempts to format with either
{:f}or{:e}and attempts to either.replace(...)or[:fixed_width]the resulting string doesn't work, because of various edge cases, where it changes the number, cuts off the mantissa or the floating point (.)