I’m writing a function that takes a number, it can either be a float or an integer, and returns an integer indicating how many significant figures that input has.
Here is an example
>>> import calculate_number_of_significant_figures
>>> calculate_number_of_significant_figures(3500)
2
Following the rules of significant figures we can conclude that every trailing zero on a floating value is significant:
3.500 has 4 significant figures
2.7400000 has 8 significant figures
and so on…
I know Python understands that 3.500 and 3.5 are equal numbers, they are just represented differently.
Given the context above, when I convert the float value to a string for manipulation and checking purposes python cuts off the trailing zeros:
>>> floating_value = 2.5000
>>> str(floating_value)
'2.5'
I would like the trailing zeros to be kept when performing this conversion.
Am I missing something?
Notes: I know that python has the format placeholder %{}.xf
to specify the decimal places, where x is the number of decimal places. But that’s not useful for my context since we have rules for defining significant figures.
There is also the decimal library that can handle floating point arithmetics and things related, but I wasn’t able to find a solution through the library since it does the same thing as converting to a string (maybe I’m doing something wrong)
>>> import decimal
>>> decimal.Decimal(2.500)
2.5