Python float: How to Use float() Function In Python

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()

Python float() is an inbuilt method that is used to return a floating-point number from a number or a  string. 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)

Parameters

  • value- It can be a number or string that converts into a floating point number.

Return

  • It returns a floating point number.

Python float() Function Example

The below example shows the working of float():

# Python example program for float() function in Python  
# for integers    
a = float(2)  
print(a)    
    
# for floats    
b = float(" 5.90 ")  
print(b)    
    
# for string floats    
c = float("-24.17")  
print(c)    
    
# for string floats with whitespaces    
d = float(" -17.15\n ")  
print(d)    
  
# string float error    
e = float(" xyz ")    
print(e)  

Output:

2.0
5.90
-24.17
-17.15
ValueError: could not convert string to float: ' xyz '

In the above example, we have given different types of inputs, like an integer, a float value, and a string value. When the argument is passed to the float() function, the output is returned in the form of a floating value.

#python #python float

Python float: How to Use float() Function In Python
4.35 GEEK