5

For example

x = 1.23
print("%.3f" % x)

Output will be "1.230" and I want "1.23". Is there any way to do? Thank you.

edited: I want a function that will print floating point at limit precision and will not print zero followed if it's not reach the limit given

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Chayanin
  • 281
  • 1
  • 5
  • 11

1 Answers1

3

If you want to output up-to 3 digits but without 0 you need to format to 3 digit and rstrip zeros:

for n in [1.23,1.234,1.1,1.7846]:
    print('{:.3f}'.format(n).rstrip("0"))  # add .rstrip(".") to remove the . for 3.00003

Output:

1.23
1.234
1.1
1.785

Have a quick read here for python 3 formattings: https://pyformat.info/#number or here: https://docs.python.org/3.1/library/string.html#format-examples

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69