Format a float in Python with a maximum number of decimal places and without extra zero padding
What you're asking for should be addressed by rounding methods like the built-in round
function. Then let the float
number be naturally displayed with its string
representation.
>>> round(65.53, 4) # num decimal <= precision, do nothing
'65.53'
>>> round(40.355435, 4) # num decimal > precision, round
'40.3554'
>>> round(0, 4) # note: converts int to float
'0.0'
Sorry, the best I can do:
' {:0.4f}'.format(1./2.).rstrip('0')
Corrected:
ff=1./2.
' {:0.4f}'.format(ff).rstrip('0')+'0'[0:(ff%1==0)]