0

what I need is similar to %.2f but so that any 0 or . endings are deleted.
An example follows, on the left are the float numbers and on the right the desired formatting.

4525.0014436  ->   '4525'
4525.0091     ->   '4525.01'
4525.1036     ->   '4525.1'
4525.163465   ->   '4525.16'
4525.998      ->   '4526'

Is there a way to get this formatted in python? Or is it necessary to do it algorithmically?

mastupristi
  • 1,240
  • 1
  • 13
  • 29

1 Answers1

0

found: just use rstrip('0.') after formatting with %.2f

for example:

>>> ("%10.2f" % 4567.001).rstrip('0.')
'   4567'
>>> ("%10.2f" % 4567.009).rstrip('0.')
'   4567.01'
>>> ("%10.2f" % 4567.1004).rstrip('0.')
'   4567.1'
mastupristi
  • 1,240
  • 1
  • 13
  • 29
  • This does not work as expected for `0` as it returns an empty string. Maybe make a special condition for `0` like: `'0' if f==0. else ('%10.2f' % f).rstrip('0.')`. Otherwise nice solution. – Scindix Jul 04 '22 at 20:04