Python float() Function

The python float() function returns a floating-point number from a number or string. A floating-point number, or float, is a mathematical value that contains a decimal point. Floats can be positive or negative and can address both whole numbers and fractional values. In Python, the float() function is utilised to switch a value completely to a float.

Python float() Function Syntax

It has the following 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.

Different Examples for Python float() Function

Here, we are going to take several examples to demonstrate the Python float() Function.

Python float() Function Example 1

The below example shows the working of the float() function in Python.

# 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 '

Explanation: 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.

Note: The important point to note is that the float() method converts only integers and strings into floating-point values. All the other arguments, like list, tuple, dictionary, and None values, result in TypeErrors.

Python float() Function Example 2

Let us take an example to demonstrate the float() function in Python.

# Python program for float() function  

# List  

list = float([11, 24, 38, 76, 100])  

# Tuple  

tuple = float(( 10, 20, 30, 40, 50 ))  

# Dictionary  

dictionary = float({ " ram ": 1000, " bheem ": 2000})  

# None  

value = float(None)  

  

print(list)  

print(tuple)  

print(dictionary)  

print(value)

Output:

TypeError: float() argument must be a string or a number, not ' list '
TypeError: float() argument must be a string or a number, not ' tuple '
TypeError: float() argument must be a string or a number, not ' dict '
TypeError: float() argument must be a string or a number, not ' NoneType '

Conclusion

To conclude, the float() function in Python is utilised to change a number or a string that addresses a number to a floating-point value. When utilised accurately, the function can assist you with changing information between various mathematical configurations and performing number-crunching tasks that require floating-point accuracy.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *