In Python, there are two number data types: integers and floating-point numbers or floats. Sometimes you are working on someone else’s code and will need to convert an integer to a float or vice versa, or you may find that you have been using an integer when what you really need is a float. Python has built-in methods to allow you to easily convert integers to floats and floats to integers.
Python’s method float() will convert integers to floats. To use this function, add an integer inside of the parentheses:
In this case, 57 will be converted to 57.0.
You can also use this with a variable. Let’s declare f as equal to 57, and then print out the new float:
By using the float() function, we can convert integers to floats.
Python also has a built-in function to convert floats to integers: int().
The int() function works similarly to the float() function: you can add a floating-point number inside of the parentheses to convert it to an integer:
In this case, 390.8 will be converted to 390.
You can also use this with variables. Let’s declare b as equal to 125.0, and c as equal to 390.8, then print out the new floats:
When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer. Even though we may want to round 390.8 up to 391, Python will not do this through the int() function.
In Python 3, relevant quotients are converted from integers to floats when doing division. That is, when you divide 5 by 2, in Python 3 you will get a float for an answer (2.5):
Write a program to demonstrate converting an Integer to a Float
Write a program to demonstrate converting an Integer to a Float and a Float to an Integer.
Write a program to demonstrate converting an Integer to a Float, a Float to an Integer and conversion by division.
Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.
Have a great day!!
K McGuinness - 2018
No personal data will be shared with any third party. The only data processed via this website is anonymous browsing data to best manage your user experience.