float() in Python | Python float() Function - Scaler Topics (original) (raw)

float() in Python | Python float() Function

3 mins readLast updated: 15 Mar 2022171 views

Python Course for Beginners With Certification: Mastering the Essentials

Python Course for Beginners With Certification: Mastering the Essentials

by Rahul Janghu

1000

Start Learning

Python Course for Beginners With Certification: Mastering the Essentials

Python Course for Beginners With Certification: Mastering the Essentials

Start Learning

Overview

In Python Programming, float() is an inbuilt function that converts an integer or specific strings into floating-point values.

Syntax of float() function in Python

Parameters of float() function in Python

It accepts only one parameter but it's optional:

Return values of float() function in Python

Argument type Input Return value Output
No argument is passed - 0.0 0.0
Integer 4 Floating point number 4.0
Floating point number 30.0 Floating point number 30.0
String "20" Floating point number 20.0
String "nan", "NaN" nan nan
String "inf", "InF", "InFiNiTy", "infinity" inf inf
String "Scaler" ValueError: could not convert string to float : 'Scaler' -

Example of float() function in Python

Let's look at an example to convert string 30 to floating-point value 30.0:

Code:

Output

What is float() function in Python?

In all programming languages, typecasting of the data has been a important feature.

Python provides us an inbuilt function to convert integers and few strings to floating point numbers. Let's see how float in Python works with different parameters:

More Examples

Example 1: How float() works in Python?

Python code to explain the working of the float() in Python.

Code:

Output:

Explanation:

The last string passed does not have a decimal point number hence the code returns ValueError.

Example 2: Converting a string into a floating-point number

Code:

Output:

Explanation:

The string passed into the float() in the Python program contains integers and hence the program returns the required floating-point value.

Example 3: Using float() with infinity and Nan(Not a number)

Code:

Output:

Only for the specified strings, the float() in Python returns the above output.

Example 4: Converting an Integer to a Float in Python

Code:

Output:

Explanation:

The above code represents when an integer is passed into the float function. The code will always return the required floating-point value in such cases.

Example 5: Python float() Exception

Code:

Output:

Explanation:

In the above code, a string is passed to the float() function to check if it is a decimal point value. But it turns out not to be, hence the code returns an error.

Conclusion