This concise article shows you a couple of different ways to get the size of a number (integer, float) in Python.
Using the bit_length() method
With integers
If you mean the number of bytes needed to represent the number as a binary value, you can use the bit_length()
method of integers and divide it by 8 (or use ceil division).
Example:
num = 2024
size_in_bytes = (num.bit_length() + 7) // 8
print(f"The size of {num} is {size_in_bytes} bytes")
Output:
The size of 2024 is 2 bytes
With floats
The bit_length()
method is only defined for integers in Python. If you want to use it with floats, you need to convert them to integers first by using struct
.
Code example (with explanations):
import struct
my_float = 20.23
# Convert to string
my_string = struct.pack('>f', my_float)
# Convert to int
my_int = struct.unpack('>l', my_string)[0]
# get the number of bits
bits = my_int.bit_length()
# get the number of bytes
bytes = (bits + 7) // 8
print(f"The number of bytes is {bytes}")
Output:
The number of bytes is 4
Using the sys.getsizeof() function
The sys.getsizeof()
function gives you the number of bytes to store your number as an object in memory.
Example:
import sys
x = 1
y = -3.33323433
print(sys.getsizeof(x))
print(sys.getsizeof(y))
Output:
28
24
sys.getsizeof()
returns the size of an object in memory, which includes the overhead of the object’s header and other information that Python needs to manage the object. This means that the size returned by sys.getsizeof()
is not the same as the size of the number itself in bytes. That’s why this approach is not the same as the first one.