The float function in Python converts a number or a string into a floating-point number. A floating-point number, commonly referred to as a float, represents a mathematical value that includes a decimal point. Floats may be either positive or negative, and they can represent both integer values and fractions. In Python, the float function is employed to transform any given value into a float type.
Python float Function Syntax
It has the following syntax:
float(value)
Parameters
- value: This can either be a numeric value or a string that can be transformed into a floating-point number.
Return
It returns a floating point number.
Different Examples for Python float Function
In this section, we will present multiple examples to illustrate the functionality of the Python float function.
Python float Function Example 1
The following example demonstrates how the float function operates 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 '
Clarification: In the preceding illustration, various kinds of inputs have been presented, including an integer, a floating-point number, and a string. When one of these arguments is supplied to the float function, the result is produced as a floating-point number.
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
Consider an example that illustrates the usage of 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
In summary, the float function in Python serves the purpose of converting either a numerical value or a string representation of a number into a floating-point format. When applied correctly, this function can aid in transforming data across diverse numerical formats and executing mathematical operations that necessitate precision in floating-point calculations.