Why str(0.20) = 0.2 instead of 0.20 in Python?

0 votes
asked Sep 12, 2017 by chong-sun

I was trying to convert a float 0.20 to a string using

str(0.20)

However, what I got was '0.2' instead of '0.20'. Does anyone know how to fix this? I tried to search on Google and stackoverflow, but I didn't find any useful answer.

Thanks in advance!

3 Answers

+2 votes
answered Sep 12, 2017 by maxnoe

You can use python's string formatting functionality. Actually there are three possibilities:

  • f-strings, since python 3.6

    value = 0.2
    print(f'{value:.2f}') # 2 digits precision
    
  • str.format

    value = 0.2
    print('{:.2f}'.format(value))
    
  • % formatting

    value = 0.2
    print('%.2f' % value)
    

For more formatting details, see https://docs.python.org/3.6/library/string.html#format-string-syntax

0 votes
answered Sep 12, 2017 by dharmesh

You can use a format string that allows you to format an number in a pre-defined way. To say that you want to format a floating point number and have two digits after the separator, use .2f:

data = 0.20

print("{0:.2f}".format(data))
0 votes
answered Sep 12, 2017 by scrutari

Answer to the question in the title is similar to this answer about __str__: it is because str is for readability, so its aim is to produce nice output rather than precise one.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...