1

I'd like to format floating numbers in such a way that at most 2 decimals are added after the dot.

1.24 should be displayed as 1.24

1.246 should be displayed as 1.25

1.2 should be displayed as 1.2

1.0 should be displayed as 1

Using "%.2f" with printf has a drawback. For numbers with less than 2 decimals after the dot, it adds trailing 0 digits. Therefore, 1.2 is displayed as 1.20 and 1.0 is displayed as 1.00.

viebel
  • 19,372
  • 10
  • 49
  • 83

1 Answers1

0

you can do a custom print, trim out tailing 0s and then tailing .

e.g. in python

def custom_print(num):
    str = ('%.2f' % num).rstrip('0').rstrip('.')
    print(str)
liusy182
  • 205
  • 1
  • 7