I need to keep track of the number of significant digits in a number (float or integer). Trailing zeroes after a decimal point are considered significant, e.g. in 12.0 there are 3 significant figures and in 12.00 there are 4. I thought to use something like len(str(number))
but this removes all but one of the trailing zeroes from floats. The format()
function and str.format()
method, often suggested for similar questions (in integer, in float, and float again) would both seemingly require me to know in advance how many decimal points I wanted. Is there a good way to go about this? Should I just require the number to be inputted as a string so that all trailing zeroes are preserved? The code I'm using to find significant figures is below. I believe that it works for all cases except that described above.
def __init__(self, value):
"""Initializes a Sigfig object with the given value and finds the number of significant figures in value"""
assert type(value)==int or type(value)==float or type(value)==Sigfig, "Sigfig value must be of type int, float, or Sigfig"
# I wanted to avoid values of type str so that I don't have to worry about inputs like Sigfig('55b')
self.value=value #This is to allow math with full value to avoid losing precision to rounding
self.valuestring=f'{value}'
#Remove leading zeroes before or after a decimal point and scientific notation
self.remlead0enot=self.valuestring.lstrip('0').lstrip('.').lstrip('0').split('e',1)[0]
#Account for ambiguous zeroes before implied decimal point e.g. 1000
if '.' not in self.valuestring and self.valuestring[-1]=='0':
self.sigfigs=len(self.remlead0enot.rstrip('0'))
#Account for floats e.g. 1.005 and ints e.g. 105
else:
self.sigfigs=len(self.remlead0enot)-1 if '.' in self.remlead0enot else len(self.remlead0enot)