Float type and its methods in python
Last Updated :
21 Feb, 2025
A float (floating-point number) is a data type used to represent real numbers with a fractional component. It is commonly used to store decimal values and perform mathematical calculations that require precision.
Characteristics of Float Type
- Floats support decimal and exponential notation.
- They occupy 8 bytes (64 bits) in memory.
- Operations involving floats may lead to rounding errors due to binary representation limitations.
Example:
Python
a = 10.5 # Float declaration
b = -3.14 # Negative float
c = 2.0 # Even if it looks like an integer, it's a float
d = 1.23e4 # Scientific notation (1.23 × 10⁴ = 12300.0)
e = 5e-3 # Scientific notation (5 × 10⁻³ = 0.005)
print(a,b,c,d,e)
Built-in Methods for float type
Python provides several built-in methods for float objects.
Built-in Methods for float
Type in Python
Method | Description |
---|
float.as_integer_ratio() | Returns a tuple representing the float as a ratio of two integers. |
---|
float.conjugate() | Returns the same float value (useful for compatibility with complex numbers). |
---|
float.fromhex(s) | Converts a hexadecimal string to a float. (Static method) |
---|
float.hex() | Returns the hexadecimal representation of the float. |
---|
float.is_integer() | Returns True if the float is an integer (has no decimal part), else False. |
---|
float.__abs__() | Returns the absolute value of the float. |
---|
float.__add__(other) | Adds two float values (self + other). |
---|
float.__sub__(other) | Subtracts two float values (self - other). |
---|
float.__mul__(other) | Multiplies two float values (self * other). |
---|
float.__truediv__(other) | Performs true division (self / other). |
---|
float.__floordiv__(other) | Performs floor division (self // other). |
---|
float.__mod__(other) | Returns the remainder of division (self % other). |
---|
float.__pow__(other) | Returns the float raised to the power of other (self ** other). |
---|
float.__round__(n) | Rounds the float to n decimal places. |
---|
1. float.as_integer_ratio()
The as_integer_ratio()
method returns a tuple of two integers, whose ratio equals the float. This method is useful for precise representation of floating-point numbers as fractions, which can help avoid floating-point precision errors in arithmetic calculations. The returned integers represent the numerator and denominator of the fraction.
Python
f = 2.75
ratio = f.as_integer_ratio()
print(ratio)
Here, 2.75
is exactly represented as 11/4
. The method breaks down the float into an exact fraction by multiplying it by a power of 2 internally and simplifying it into two integers.
2. float.conjugate()
The conjugate()
method returns the same float value. This method exists primarily for compatibility with complex numbers, where the conjugate of a complex number negates its imaginary part. Since a float has no imaginary part, calling conjugate()
on a float simply returns itself.
Python
f = 5.5
print(f.conjugate())
This method does not modify the float; it just returns the same value. It ensures compatibility when working with complex numbers, where the conjugate of a + bi
is a - bi
.
3. float.fromhex(s)
The fromhex()
method converts a hexadecimal string representation of a floating-point number into a float. This is useful when dealing with binary representations or low-level floating-point operations.
Python
s = "0x1.91eb851eb851fp+1"
a = float.fromhex(s)
print(a)
The hexadecimal string represents a floating-point number in scientific notation. The p+1
denotes a power of two exponent. Converting from hexadecimal ensures precise representation of binary floating-point numbers.
4. float.hex()
The hex()
method returns the hexadecimal representation of a float. This is useful for debugging floating-point precision issues and for storing exact binary representations.
Python
Output0x1.91eb851eb851fp+1
The output is a hexadecimal scientific notation representing the float. The p+1
means multiplying by 2^1
. This format is useful for exact floating-point storage and computation.
5. float.is_integer()
The is_integer()
method checks if a float has no decimal part and returns True
if it is equivalent to an integer. This is useful when working with numerical computations where integer-like behavior is required.
Python
print((4.0).is_integer())
print((4.5).is_integer())
Here, 4.0
is equivalent to the integer 4
, so is_integer()
returns True
. However, 4.5
has a decimal part, so it returns False
.
6. float.__abs__()
The __abs__()
method returns the absolute value of a float, which is the non-negative version of the number. It is equivalent to the built-in abs()
function.
Python
f = -7.3
print(f.__abs__())
print(abs(f))
The negative value -7.3
is converted to its positive equivalent 7.3
. This is useful when working with distances, magnitudes, or other computations where only the positive value is needed.
7. float.__add__
The __add__()
method performs addition between two float values. This is automatically used when we use the +
operator.
Python
a = 5.5
b = 2.2
print(a.__add__(b))
print(a + b)
Here, 5.5 + 2.2
results in 7.7
. The +
operator internally calls the __add__()
method.
8. float.__sub__
The __sub__()
method performs subtraction between two float values. It is used when we apply the -
operator.
Python
a = 10.5
b = 3.2
print(a.__sub__(b))
print(a - b)
Here, 10.5 - 3.2
results in 7.3
. The -
operator calls __sub__()
internally.
9. float.__mul__(other)
The __mul__()
method performs multiplication between two float values.
Python
a = 4.2
b = 2.0
print(a.__mul__(b))
print(a * b)
Multiplication of 4.2 * 2.0
results in 8.4
. The *
operator invokes __mul__()
internally.
10. float.__truediv__(other)
The __truediv__()
method performs true division (returns a float even when dividing two integers).
Python
a = 7.5
b = 2.5
print(a.__truediv__(b))
print(a / b)
The division 7.5 / 2.5
results in 3.0
, ensuring a floating-point output.
11. float.__floordiv__(other)
The __floordiv__()
method performs floor division, which returns the largest integer less than or equal to the quotient.
Python
a = 7.5
b = 2.5
print(a.__floordiv__(b))
print(a // b)
The quotient is 3.0
with no remainder, so the floor division is the same as normal division here.
12. float.__mod__(other)
The __mod__()
method returns the remainder of division.
Python
a = 10.5
b = 4.0
print(a.__mod__(b))
print(a % b)
Here, 10.5 / 4.0
results in 2
with a remainder of 2.5
.
13. float.__pow__(other)
The __pow__()
method raises the float to the power of another number.
Python
a = 3.0
b = 2.0
print(a.__pow__(b))
print(a ** b)
The expression 3.0 ** 2.0
calculates 3.0
raised to the power of 2.0
, which is 9.0
.
14. float.__round__(n)
The __round__()
method rounds the float to n
decimal places.
Python
f = 3.14159
print(f.__round__(2))
print(round(f, 2))
The float 3.14159
is rounded to 3.14
when specifying 2
decimal places.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read