Is there a way to determine if a number is storable as a single-float or double-float?
I'm implementing my own database format and in my helper function num2bin(n)
I currently have the follwoing code:
import struct, warnings
def num2bin(n:int|float) -> bytes:
match type(n).__name__:
case 'int':
... # Excluded because unimportant to this question
case 'float':
try:
return struct.pack('>f', n)
except struct.error:
try:
return struct.pack('>d', n)
except struct.error:
warnings.warn(f"num2bin(n): Failed to store {n} as float or double")
return b''
case other:
warnings.warn(f"num2bin(n): 'n' is of type '{other}' (must be 'int' or 'float')")
return b''
Is there a better and more elegant way to determine whether I can store the number as float (f
) or double (d
)?
I think there must be a better way to do that than just try it and catching errors?