Wednesday, March 25, 2015

How to Convert Number Types in Python - Python Numbers - Python Tutorial

How to Convert Number Types in PythonHow To Convert Number Types in Python


In this Python tutorial, we are going to explore how to convert number types in Python. When coding sometimes we need in order to convert our current integer to a float or our current float to integer. We can also convert strings to either integers or floating point numbers.  Python has a built-in function that will give us the ability to do this.


Int() Built-in Function


The int() built-in function gives the ability to convert either a floating point number to an integer or convert a string to an integer. The int() function will always round down when converting floating point numbers. We also cannot convert floating point number strings to integers but we can do it we will look at that later in this tutorial. Let’s take a closer look at some int() examples.


#int() built-in function

#convert floats to integers
>>> int(4.5)
4
>>> int(1.45643)
1

#convert string integers to integers
>>> int("5")
5
>>> int("9")
9


Float() Built-in Function


The float() built-in function gives us the ability to convert integers to floating point numbers and convert strings to floating point numbers let’s take a closer look at this example.


#float() built-in function

#Convert integer to float
>>> float(6)
6.0

#convert integer to float
>>> float(-78)
-78.0

#convert integer in a string to a floating point number
>>> float("5")
5.0

#convert a floating point number string to a actual floating point number
>>> float("6.7")
6.7

Converting a String Floating Point Number To A Real Integer


#just using int will not work
>>> int("6.7")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '6.7'

#first convert to float then to integer
>>> int(float("6.7"))
6

Checking The Type Of An Object


We can also use the type() built-in function to check the type of an object.


#type()

>>> type(6)
<class 'int'>
>>> type(())
<class 'tuple'>
>>> type(7.6)
<class 'float'>
>>> type("")
<class 'str'>

Conclusion


 


In this Python tutorial, we took a look at How to Convert Number Types in Python. These built-in functions help us with our code so we do not have to build our own function to convert the number types. If you have any questions about this tutorial please leave a comment below.



No comments:

Post a Comment