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.
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.
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).
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
Python string to float conversion
How to use the float() command to create 2 decimal places instead of one in a product of 2 numbers [the product is dollar amount]
Floating point numbers to two decimal places - possible with standard lib?
python - Float string number to float with 2 decimals? - Stack Overflow
Hi all, I have a string a = '1721244344.700249000', I want to convert it to a floating value.
Float() is returning only 2 places after decimal point. Like 1721244344.7
Is there a way I can convert the entire string to a floating point value and get all the decimal (upto 9 places after decimal point)?
I have to use python v2.7 for this.
Edit: I do not have problem in printing the all 9 decimal places but I need the floating value so that I can subtract another value so that I get the difference with accuracy upto 9 th decimal point.
Example:
hourlyRate = 20 hoursLabor = 1.6
I want the answer to show “32.00” instead of “32” or “32.0”.
What I have so far produces the number 32.0:
totalPay = float(hourlyRate * hoursLabor)
print(totalPay)
I’m obviously very new at this. Just getting some beginner’s practice :)