Python float() function


The float() function in Python is used to convert a given value into a floating-point number. If no argument is provided, it returns 0.0.

Syntax

float([x])
  • x (optional): The value to be converted to a floating-point number. It can be a string, integer, or any object that implements the __float__() method.

Return Value

  • Returns the floating-point representation of the input value.
  • Raises a ValueError if the input cannot be converted to a float.

Examples

  1. Converting an integer to a float:

    print(float(5)) # Output: 5.0
  2. Converting a string to a float: The string must represent a valid number.

    print(float("3.14")) # Output: 3.14 print(float("5")) # Output: 5.0
  3. Using float() without arguments: When called without arguments, float() returns 0.0.

    print(float()) # Output: 0.0
  4. Converting a scientific notation string: float() can handle strings in scientific notation.

    print(float("1e3")) # Output: 1000.0
  5. Using float() with an object: Any object that defines the __float__() method can be passed to float().

    class MyNumber: def __float__(self): return 7.5 num = MyNumber() print(float(num)) # Output: 7.5
  6. Handling special float values: You can also convert special values like "NaN" (Not a Number) or "inf" (infinity).

    print(float("nan")) # Output: nan print(float("inf")) # Output: inf

Handling Errors

  • If the string does not represent a valid number, Python will raise a ValueError:
    print(float("abc")) # Raises ValueError: could not convert string to float

Summary

  • The float() function converts a value to a floating-point number.
  • It works with integers, strings, and objects that define __float__().
  • If no argument is given, it returns 0.0.
  • It can handle scientific notation and special float values like "NaN" and "inf".