Just use float("3")
to achieve that but notice that a float
does not have a specific number of digits after the decimal point; that's more a feature of outputting a float
using string formatting. So you can use '%.2f' % float("3")
to see your float
value with two decimal digits.
Your tests were all flawed in several aspects.
va = '%.2f' % float('3')
created a str
which looked like a float, not a float
.
vb = float('%.2f' % float('3'))
created a decent float
but your printing test print vb
then did not format the float
to using two decimal digits after the point. It just used the default formatting (which prints one trailing .0
to make clear that this is not an int
).