I am trying to create a function to convert an integer into standard form (a * 10 ** n, where 1 ≤ a < 10). I have the following code, which raises countless errors and most likely does not work, but you can see my approach:
# The power of ten is always the amount of digits minus one
power = len(str(num)[:-2]) - 1
# Count trailing zeroes (until a number not zero)
zero_count = 0
for digit in reversed(str(num)[-2]):
print(digit)
if digit == "0":
zero_count = 1
else:
break
# Chop the trailing zeroes off the end
add = str(num)[:-zero_count]
# Divide the add until it is less than ten
while add > 10:
add = add / 10
# Formatting
standard_form = f"{add} * 10 ** {power}"
However, nothing I have done to debug it has worked. How can I convert number N into standard form?
CodePudding user response:
I would use a recursive function:
def sform(add, power=0):
if 1 <= abs(add) < 10:
return add, power
elif 0 < abs(add) < 1:
return sform(add*10, power-1)
elif add == 0:
return (0, 0)
return sform(add/10, power 1)
def test_sform(num):
add, power = sform(num)
print(f"{add} * 10 ** {power}")
Tests:
>>> test_sform(234864897363)
2.34864897363 * 10 ** 11
>>> test_sform(-1234)
-1.234 * 10 ** 3
>>> test_sform(0.5)
5.0 * 10 ** -1
>>> test_sform(1.375e-06)
1.3749999999999998 * 10 ** -6
>>> test_sform(-0.75)
-7.5 * 10 ** -1
>>> test_sform(10)
1.0 * 10 ** 1
>>> test_sform(1)
1 * 10 ** 0
>>> test_sform(0)
0 * 10 ** 0