Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Science USbreadcumb forward arrow iconFloat in Python: A Step by Step Guide

Float in Python: A Step by Step Guide

Last updated:
31st Aug, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Float in Python: A Step by Step Guide

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.

What is Float in Python?

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

Ads of upGrad blog

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.

How does Float in Python work? Examples of Float() Method

Here’s looking at the different functions you can perform on the float:

1. Convert an Integer to a Float in Python

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.

2. Convert a String to a Float in Python

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

3. Typecasting using Float()

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. 

4. Rounding Float in Python

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) 

  • The two arguments float_num and num_of_decimals indicate the float you want to round and the decimal place you want it to be rounded to respectively. 
  • num_of_decimals is optional as we mentioned above. 
  • If num_of_decimals is a negative integer, the Python round float function will round it to the digit occurring before the decimal point. 

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

5. Generating Python Random Float

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)

  • Both arguments in the uniform() function are compulsory. Skipping anyone would lead to a TypeError uniform().
  • start represents the lower limit of the range. It assumes the value to be 0 by default.
  • stop represents the upper limit or the last number in the range. 

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:

  • If start is less than or equal to the stop, a random float number will be generated that is <= the stop number and >= the start number.
  • If stop is greater than or equal to start, the Python random float number will be >= stop number and <= the start number.

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.

Learn Python to Progress your Career in Data Science

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:

Enjoy the upGrad Learning Experience!

Ads of upGrad blog

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Data Science Courses

Frequently Asked Questions (FAQs)

1 What is the difference between double and float?

Float is 32 bits whereas double is 64bits. It has a larger mantissa and reduces precision inaccuracies significantly.

2Is Python better than R?

Both programming languages have their unique advantages. While R is an excellent option for statistical learning, Python is better suited for artificial intelligence and machine learning, and data analysis. It allows you to develop large-scale applications.

3 Is data science a good career option?

Data science is acknowledged as a promising job role in the US and has reportedly seen a 56% surge in job openings. It is also one of the highest-paid jobs. The average salary of a data scientist is $120,092 per year.

Explore Free Courses

Suggested Blogs

Top 10 Real-Time SQL Project Ideas: For Beginners &#038; Advanced
14861
Thanks to the big data revolution, the modern business world collects and analyzes millions of bytes of data every day. However, regardless of the bus
Read More

by Pavan Vadapalli

28 Aug 2023

Python Free Online Course with Certification [US 2024]
5519
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Pavan Vadapalli

14 Apr 2023

13 Exciting Data Science Project Ideas &#038; Topics for Beginners in US [2024]
5474
Data Science projects are great for practicing and inheriting new data analysis skills to stay ahead of the competition and gain valuable experience.
Read More

by Rohit Sharma

07 Apr 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
6063
Data refers to the collection of information that is gathered and translated for specific purposes. With over 2.5 quintillion data being produced ever
Read More

by Rohit Sharma

06 Apr 2023

Best Python Free Online Course with Certification You Should Check Out [2024]
5627
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Rohit Sharma

05 Apr 2023

5 Types of Binary Tree in Data Structure Explained
5385
A binary tree is a non-linear tree data structure that contains each node with a maximum of 2 children. The binary name suggests the number 2, so any
Read More

by Rohit Sharma

03 Apr 2023

42 Exciting Python Project Ideas &#038; Topics for Beginners [2024]
5855
Python is an interpreted, high-level, object-oriented programming language and is prominently ranked as one of the top 5 most famous programming langu
Read More

by Rohit Sharma

02 Apr 2023

5 Reasons Why Python Continues To Be The Top Programming Language
5339
Introduction Python is an all-purpose high-end scripting language for programmers, which is easy to understand and replicate. It has a massive base o
Read More

by Rohit Sharma

01 Apr 2023

Why Should One Start Python Coding in Today’s World?
5220
Python is the world’s most popular programming language, used by both professional engineer developers and non-designers. It is a highly demanded lang
Read More

by Rohit Sharma

16 Feb 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon