Python float() Function Explained with Examples

Python Float Function

In this article, we will see what is and various examples of “Python Float Function”. It will help you in implementing this concept and get a tight grip over this. 

What is the Python float() method?

The Python float() function is a built-in Python function that converts the given value (number or string) into a floating-point number and returns the result. If the float() method fails to convert string to float then it raises the ValueError.

The Syntax of float() is:

float(Parameter value)

Parameter Value:

A number or a string that can be converted into a floating-point number. 

Parameter is optional. If there is no parameter then it returns 0.0.

Note: If the value is a string then it should contain a decimal point and the valid argument should contain some numeric value.

Return Values

The float() function returns a floating-point value equivalent to the number passed as is or in the form of a string.

Errors

This method raises exceptions when it receives invalid parameter value.

  1. ValueError
  2. TypeError

ValueError – Python ValueError is raised when a Python function receives an argument of the correct type but a wrong value.

TypeError – Python TypeError is raised when a Python function receives an argument is not of the expected type

Python float() function examples

Example 1: float() function with +ve number values

Let’s pass positive values and see how float() method converts to an equivalent floating-point value.

Output:

Example 2: float() function with -ve number values

Let’s pass negative values and see how float() method converts to an equivalent floating-point value.

Output:

Example 3: float() function with a string containing numbers

Let’s pass a number in string format and see how float() method converts to an equivalent floating-point value and returns the result.

Output:

Note: It ignores the leading and trailing spaces

Example 4: float() for Infinity, Inf and Nan(Not a number)

It also accepts words like infinity and Nan(Not a number).

Output:

Example 5: float() with invalid inputs

Let’s pass some invalid input values and find how float() method operates with the wrong parameter values.

Output:

Also read:

Python Float Function

Get our latest blog posts delivered to your inbox

Subscribe and get popular blog posts about software testing industry.

Rajkumar

Leave a Comment

Share via
Copy link
Powered by Social Snap