Question

I am trying to turn str '3' into float 3.00

va = '%.2f' % float('3')
print va
print isinstance(va, float)

3.00
False

---

vb = float('%.2f' % float('3'))
print vb
print isinstance(vb, float)

3.0
True

I need code that outputs

3.00  # correct decimal places
True  # is float
Was it helpful?

Solution

You are confusing float values with their string representation. float(3) is enough, and whenever you need to print one, use formatting.

va = float('3')
print format(va, '.2f')
print isinstance(va, float)

float objects themselves have no concept of a number of decimal places to track.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top