I would like to keep the total number of digits (before and after the decimal point) of a float constant in python.
For example, if I want to impose a fixed width of 7: 1234.567890123 would become 1234.567 but 12345.678901234 would become 12345.67
Fixing the number of decimals does not work in this case since it depends on how many digits I have before the decimal point. I also tried the [width] option but it impose a minimum width and I need a maximum.
Thanks for your input!
You can set the precision when using decimal
It sounds like you also want to round down, but could choose other rounding options if you like. You create a context that includes the precision, rounding logic, and a few other options. You can apply the context to all future operations with
setcontext
, a single number usingnormalize
, or with a context manager usinglocalcontext
.The simplest solution is probably to use the exponential format with one less than the number of digits.
I ended up writing this solution that can print floats as well as exponentials but it's probably unnecessarily long for most needs.
Just by using your example,