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:
>>> 1.5
1.5
>>> float("3.14")
3.14
float Constructors
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:
>>> float()
0.0
Creating floats using literals, including scientific notation:
>>> 3.14
3.14
>>> -0.5
-0.5
>>> 1e-3
0.001
Creating floats using the class constructor:
>>> 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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- How to Format Floats Within F-Strings in Python (Tutorial)
- The Python math Module: Everything You Need to Know (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Formatting Floats Inside Python F-Strings (Course)
- Format Floats Within F-Strings (Quiz)
- Exploring the Python math Module (Course)