AppDividend
Latest Code Tutorials

Python float() Example | float() Function In Python Tutorial

0

Python float() is an inbuilt method that is used to return a floating-point number from a number or a string. The float() function converts the specified value into a floating-point number. The float() method only accepts one parameter and that is also optional to use.

Python float()

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)

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, inf (lowercase or uppercase).

 

#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

#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

Finally, Python float() Example Tutorial is over.

Leave A Reply

Your email address will not be published.

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