Programs

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

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. 

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. 

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!

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.

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.

Is 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.

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.

Prepare for a Career of the Future

0 replies on “Float in Python: A Step by Step Guide”

Accelerate Your Career with upGrad

Our Best Data Science Courses

×