0

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!

pvg
  • 2,673
  • 4
  • 17
  • 31
孙文趋
  • 577
  • 6
  • 13
  • 5
    Because `str` doesn't know your formating requirements - us `format`, e.g. `format(0.2, '.2f')` – AChampion Sep 12 '17 at 18:03
  • That works! Thanks! – 孙文趋 Sep 12 '17 at 18:04
  • 1
    The value of the float is 0.2. As far as the float is concerned, there is no difference between 0.2 and 0.20. If you want to format the string a particular way, you'll need to use a formatter. https://docs.python.org/2/library/string.html#format-examples – pvg Sep 12 '17 at 18:04
  • It's not only in python, but in any language. I believe you could specify the precision somehow, when converting a number to a string - I don't know much about python, but in several languages you can do such a thing... – Leonardo Alves Machado Sep 12 '17 at 18:05

3 Answers3

2

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

MaxNoe
  • 14,470
  • 3
  • 41
  • 46
0

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))
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17
0

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.

scrutari
  • 1,378
  • 2
  • 17
  • 33