Float in Python: A Step by Step Guide
By Rohit Sharma
Updated on Dec 21, 2023 | 7 min read | 6.3k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Dec 21, 2023 | 7 min read | 6.3k views
Share:
Programmers employ different data types (strings, integers, complex numbers, float) to store values depending on how they wish to manipulate a value. For example, you might want to run a mathematical operation but if your data type is a string, it will result in an error. Similarly, if you use a decimal number as input, you can not use integers for that.
As a primitive element of programming, Python allows programmers to create floating-point objects. The built-in function float() in Python lets you convert data types like integers or strings to floating-point numbers.
In this article, we will understand how float in Python works and explore different float methods with examples. We will also look at how we can use Python round float to include additional parameters when rounding and find out how a Python random float is generated. So, let’s get started.
Float, in computer science, is a data type that denotes a fraction or a number in the decimal format. It allows programmers a greater degree of precision when compared to integers
In Python, we use the float() method to return a float data type when the input is any specified value, string, or number
Syntax
float(value) // where value is either a string or a number
It’s optional if you want to pass a parameter or not. The default value of float() is 0.0. If the built-in float() method is unable to return a float point number from a string or number, it will raise the ValueError. It will also return an error if the integer you pass is beyond the Python float() range.
Floating-point numbers play a significant role in programming, especially when denoting currencies. They are highly efficient at providing processing power in graphic libraries where they are used extensively. Since it can tolerate rounding errors arising from the precision of up to seven digits, float can help you write more precise and accessible code.
Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Here’s looking at the different functions you can perform on the float:
Converting an integer into a floating-point number in Python is straightforward. Here’s an example
float_no = float(15)
print(float_no)
Output: 15.0.
A string in Python is considered a collection of characters. To convert a string to a floating-point number using the float() method, the string must be expressed in the numerical format. Here’s an example:
float_str = float(“15”)
print(float_str)
Output: 15.0.
If you add the positive (+) or negative (-) signs to the string, the method will convert the string to a positive float or negative float, respectively
whether you want your string to be converted to a positive float or a negative float. For example:
float_str = float(“-15”)
print(float_str)
Output: -15.0
Floats can also be expressed in scientific notation where E or e denotes the power of 10. For example, 1.5e3 = 1.5 x 103 = 1500).
Here’s an example:
print(float(2e-002))
print(float(“2e-002”))
print(float(‘+1E3’))
Output:
0.02
0.02
1000.0
You can also include invalid numbers or infinity values in the string: NaN, infinity, or inf.
For example:
print(“True: “, float(True))
print(“False: “, float(False))
print(“Nan: “, float(‘nan’))
print(“Infinity: “, float(‘inf’))
Output
True: 1.0
False: 0.0
Nan: nan
Infinity: inf
We will now use float() to find out how it works with strings and integers. In the following program, we will convert the type from integer to float:
s=100
print(“s=”,s)
print(“Before: “,type(s))
s=float(s)
print(“s=”,s)
print(“After: “,type(s))
Output:
s= 100
Before: <class ‘int’>
s= 100.0
After: <class ‘float’>
If the input is not an integer and is instead a string, it will still convert it into a floating point number. However, if the string contains characters, it will result in ValueError.
If you want an approximate value for your floating-point number that isn’t excessively precise, you can round it to the decimal point you require. For example, rounding the floating-point number to 5.1235 rounded to the hundredths place is 5.12.
In Python, there is a built-in function Round() that helps you round a float number. Python round float returns a float that is rounded as per the input you provide. In case the decimal place is not specified, Python takes it to be as 0 and then rounds it to the nearest integer.
Syntax: round(float_num, num_of_decimals)
Let’s understand this with an example:
float_num1 = 11.7
float_num2 = 11.4
float_num3 = 11.2345
float_num4 = 11.5678
float_num5= 123.45
print(round(float_num1))
print(round(float_num2))
print(round(float_num3, 2))
print(round(float_num4, 2))
print(round(float_num5, -1))
Output:
12
11
11.23
11.57
120.0
You can use the random() and uniform() methods in Python to generate random floating point numbers in the range you specify.
Let’s assume our range is 0 to 1 and we want to generate 3 random float numbers:
import random
x = random.random()
for i in range(3):
print(random.random())
Run
Output:
0.54134241344332134
0.13142525490547756
0.75132452526261544
Next, we are going to use the uniform() method to specify a range to generate random float numbers. Your range could be 1 to 10 or 32.5 to 52.5, and so on.
Syntax: random.uniform(start, stop)
Here’s a short program explaining Python random float generation:
import random
print(random.uniform(10.5, 75.5))
print(random.uniform(10, 100))
Output:
27.23469913175497
81.77036292015993
Here are some important points to remember:
This essentially implies that whether you specify the range as 1 to 10 or 10 to 1, the random.uniform() function will treat it as the same.
Check out Python tutorial concepts Explained with Examples.
Python is highly scalable and one of the fastest processing languages when compared to the likes of R, Matlab, and Stata, and thus, plays an integral role in data science. It offers the flexibility and versatility to approach a given problem in multiple ways. So, if you are looking to establish a career in data science, it is highly recommended that you build expertise in Python by learning the basic and advanced concepts of the programming language to apply to real-world scenarios. Here’s how:
Our Executive PG Programme in Data Science from IIIT Bangalore spans 12 months and is designed for freshers and mid-level managers. Students are taught in-demand, industry-relevant skills depending on the curriculum of the specialization tracks they opt for: Data Science Generalist, Deep Learning, Natural Language Processing, Business Intelligence/Data Analytics, Business Analytics, and Data Engineering.
What’s even more impressive is upGrad’s paid learner base of 40,000 is spread across 85+ countries. Its significance in global networking and peer-to-peer learning is undeniable. As you interact with peers from diverse backgrounds, your knowledge base will expand inevitably! The course provides access to over 400 hours of learning content and 20+ live classes and expert sessions from leading faculty and industry leaders who also provide 360-degree career assistance.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources