0

Considering the code below. The output of this is 2.76 but for the application I am using it for, the zero after 2.76 is significant thus I am searching for a way to output 2.760.

f = 2.7598
r = round(f,3)
s = str(r)
print(s)
  • [`str.format`](https://docs.python.org/3/library/stdtypes.html#str.format) should help. – Michael Butscher Jan 10 '20 at 03:32
  • If your application is "decimal-centric" and the idea of significant digits/precision is important to you, consider using the decimal library https://docs.python.org/3/library/decimal.html – Hymns For Disco Jan 10 '20 at 03:48

1 Answers1

1

You could remove the conversion to string and use simply use format():

f = 2.7598
r = round(f,3)
print(format(r, '.3f'))

Result:

2.760

Or if you need a string for whatever reason:

f = 2.7598
r = round(f,3)
s = format(r, '.3f')
print(s)
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • The formatting will round too, so if the value doesn't need to be rounded for mathematical purposes, just for display, you can `format` without the `round` call. – ShadowRanger Jan 10 '20 at 04:03