float

The built-in float data type represents floating-point numbers, which are numbers with a decimal point. You can create floats using literals, the float() constructor, or by converting strings or other numeric types:

Python
>>> 1.5
1.5
>>> float("3.14")
3.14

float Constructors

Python Syntax
float(number=0.0)
float(string)

Arguments

Argument Description
number A numeric value (integer or float) to convert to a float.
string A string representing a float. Required argument.

Return Value

  • Returns a Python float object

float Examples

Creating a zero instance of a float:

Python
>>> float()
0.0

Creating floats using literals, including scientific notation:

Python
>>> 3.14
3.14
>>> -0.5
-0.5
>>> 1e-3
0.001

Creating floats using the class constructor:

Python
>>> float(42)
42.0
>>> float("3.14159")
3.14159

float Methods

Method Description
.as_integer_ratio() Returns a pair of integers whose ratio is exactly equal to the original float.
.is_integer() Returns True if the float instance is finite with an integral value, and False otherwise.
.hex() Returns a representation of a floating-point number as a hexadecimal string.
.fromhex(string) Constructs a float from a hexadecimal string.

float Common Use Cases

The most common use cases for the float data type include:

  • Performing arithmetic operations with decimal numbers
  • Representing scientific data using scientific notation
  • Conducting financial calculations where fractional values are needed
  • Handling measurements with precision

float Real-World Example

Consider a scenario where you need to calculate the area of a circle with a given radius using the formula area = π * radius^2. This involves floating-point arithmetic to manage precision:

Python
>>> import math
>>> radius = 5.5
>>> area = math.pi * radius**2
>>> area
95.03317777109125

In this example, the float data type is crucial for handling the precision of the calculation, allowing for an accurate representation of the area.

Tutorial

Numbers in Python

In this tutorial, you'll learn about numbers and basic math in Python. You'll explore integer, floating-point numbers, and complex numbers and see how perform calculations using Python's arithmetic operators, math functions, and number methods.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 6, 2024 • Reviewed by Dan Bader