The float Type in Python

Life is 10% what happens to us and 90% how we react to it. If you don't build your dream, someone else will hire you to help them build theirs.

The float Type in Python

Let’s discuss the Python float type. If you assign a numerical value, with a decimal point included, then Python will automatically assign that the float type. The float type is very similar to the int type discussed previously. Although, when you’re doing assignments, you are going to need to do assignments including a decimal point. You can also do assignments with the float class .fromhex method, and use a hexadecimal value without any special prefix, and it will automatically create a decimal value, base 10, with the floating point representation. We can see that, if we run this program with Run menu, Run Module, that y is 10.0, the decimal value of A, a hexadecimal value.

x = 5.0 
 y = float.fromhex('A') 
 print('x =', x, ',', 'y=', y) 
 print('x.as_integer_ratio() =', x.as_integer_ratio())
 print('y.hex() =', y.hex()) 
 # Typical comparisons can be made 
 print('x== y =', x == y) 
 print('x != y =', x != y) 
 print('x >= y =', x >= y)
 print('x > y =', x > y) 
 print('x <= y =', x <= y) 
 print('x < y =', x  
 x = 5.0 , y = 10.0 x.as_integer_ratio() =(5, 1) 

Float objects have a as integer ratio method that will show you the ratio, like 5:1, is the ratio which represents 5.0.

They also support the inline notation for addition, subtraction, multiplication, and division as did the integer types. You can use multiple assignments, when creating your floating points, by using the first value comma, the second value equals the first value comma, the second value. So in this case, x will be assigned the value 4, and y will be assigned the value 2.0. Bit-wise operators cannot be used on the float type. Although they were able to be used on the int type. One last word I’ll leave you with about the float type, is that it is subject to rounding errors. And if you want to use a type that is more accurate, without rounding errors, then you may consider using the decimal module.