0

for a string:

0.1 --> 0.10
0.2 --> 0.20
0.3 --> 0.30
0.35 --> 0.35

Example:

print(str(round(variableB.count('X') /len(variableA), 2)))

I tried print("%.2f" %str(round(variableB.count('X')/len(variableA),2))), but I got TypeError: must be real number, not str

then I tried

print ("%.2f" % int(str(round(variableB.count('X') /len(variableA), 2))))

but I got TypeError: invalid literal for int() with base 10: '0.47'

same result with "%02d" %

3 Answers3

3

An f-string (added in Python 3.6) is a perfectly valid way to accomplish this.

>>> num = 3.1
>>> f"{num:.2f}"
'3.10'

Using %:

>>> "%.2f" % num
'3.10'

Both specify two digits of precision when displaying a floating point number.

Chris
  • 26,361
  • 5
  • 21
  • 42
1

You can just use the % for string interpolation. This will work in more Python versions than using f-strings. For example:

def printZero(num):
    print("%.2f" % num)


printZero(0.1)  # => 0.10
printZero(0.2)  # => 0.20
printZero(0.3)  # => 0.30
printZero(0.35)  # => 0.35
Michael M.
  • 10,486
  • 9
  • 18
  • 34
1
a = 0.1
b = 0.2

#old formatting
print("%.2f"%a) # output 0.10

# f-strings in 3.5+
print(f"{b:.2f}") # output 0.20
nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12