Python float: The Complete Guide

The float() function converts the specified value into a floating-point number. 

Python float

Python float() is a built-in method to return a floating-point number from a number or a string. The float() method only accepts one parameter, which is also optional.

The float() method returns:

  1. Equivalent floating-point number if an argument is passed
  2. 0.0 if no arguments passed
  3. OverflowError exception if the argument is outside the range of Python float.

Syntax

float(value)

Arguments

It takes one parameter, which is value, and that is optional. A value is a number or a string that can be converted into a floating-point number.

See the following code example.

# app.py

data = float(11)
print(data)

See the following output.

➜  pyt python3 app.py
11.0
➜  pyt

Different parameters with float()

Float number Use as a floating number
Integer Use as integer
String Must contain decimal numbers.
Leading and trailing whitespaces are removed.
Optional use of “+”, “-” signs.
It could contain NaN, Infinity, and inf (lowercase or uppercase).

 

Python float() for infinity and Nan

See the following code example.

# app.py

print(float("NaN"))

print(float("inf"))
print(float("infinity"))

We have tried to convert the NaN and infinity into the float point number. See the following output.

➜  pyt python3 app.py
nan
inf
inf
➜  pyt

Python float() for String

See the following code example.

# app.py

print(float("11.21"))
print(float("19.21"))

See the following output.

➜  pyt python3 app.py
11.21
19.21
➜  pyt

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.