I want to format a list of floating-point numbers with at most, say, 2 decimal places. But, I don't want trailing zeros, and I don't want trailing decimal points.
So, for example, 4.001
=> 4
, 4.797
=> 4.8
, 8.992
=> 8.99
, 13.577
=> 13.58
.
The simple solution is ('%.2f' % f).rstrip('.0')
('%.2f' % f).rstrip('0').rstrip('.')
. But, that looks rather ugly and seems fragile. Any nicer solutions, maybe with some magical format flags?
round()
function: docs.python.org/2/library/functions.html#roundround
simply because I am nervous I'll get1.1000000000009962
as an output someday..0
. The other question permits that.int()
will get rid of the.0
, but use in caution as it will get rid of any other decimal places (so perhaps an if/else statement?)if/else
, or I would just condition on the'.%2f' % f
or something. (Still weirdly difficult to have a nice solution...I'm really used to things being really easy in Python)