Compare the number of significant digits in two numbers

For the coding exercises I'm working on, I'm trying to compare two numbers and choose the one with the most significant numbers.

For example: compare 2.37e+07and 2.38279e+07, select 2.38279e+07, because it has more significant numbers.

I do not know how to implement this in Python. I counted counting the length of each number using len(str(NUMBER)), but this method returns “10” for both numbers above, because it does not distinguish between zero and nonzero digits.

How can I compare the number of significant digits in Python?

+4
source share
3 answers

len(str(NUMBER).strip('0')), .

, len(str(NUMBER).replace('.','').strip('0'))

, python-float - , .

+2

, , :

import re

l = re.compile(r'(\d*?)(0*)(\.0?)')

>>> l.match(str(2.37e+07)).groups()[0]
'237'
+1

:

sf1 = "2.3723805"
addsf1 = 0
decimal = False
for num in sf1:
    if decimal == True:
        addsf1 = addsf1 + int(num)
    if num == ".":
        decimal = True
print(addsf1)

, , . , , . , . , .

, .

0
source

Source: https://habr.com/ru/post/1626044/


All Articles