Search code examples
pythonstringsignificant-digits

Keep significant zeros using str(float) in python


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)

Solution

  • 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)