How to find the lowest place value in a number

Question:

I am writing a program that takes percent errors into consideration and one thing I would like to be able to do is find the lowest-place value in a number.

Example:

1000 has the lowest place of 1    
12.0 has the lowest place of 0.1    
3.1415 has the lowest place of 0.0001    
etc...

Is there a built-in function I could use or is there a simple operation I could write?

Asked By: Griffin Neal

||

Answers:

No builtin function

But this function is able to find the value you are looking for.

def e_reformat(s_number: str) -> str:
    try:
        e_index = s_number.index("e")
    except ValueError:
        return s_number
    e_number = int(s_number[e_index + 1 :])
    prefix_number = s_number[:e_index].replace(".", "")
    return f'0.{"0"*(-e_number-1)}{prefix_number}'

def lowest_place(number: float | str) -> str:
    s_number = e_reformat(str(number).lower())
    try:
        dot_index = s_number.index(".")
    except ValueError:
        return "1"
    after_dot = s_number[dot_index + 1 :]
    return f"0.{'0' * (len(after_dot) - 1)}1"

Tests:

>>> lowest_place(1000)
'1'
>>> lowest_place(12.0)
'0.1'
>>> lowest_place(3.1415)
'0.0001'
>>> lowest_place('1.00')
'0.01'
>>> 1.2e-9 == 0.0000000012, lowest_place(1.2e-9) == lowest_place('0.0000000012')
(True, True)

⚠️lowest_place(1.) or lowest_place('1.') returns '0.1'. If you expect the value to be '1', use this lowest_place function instead:

def lowest_place(number: float | str) -> str:
    s_number = e_reformat(str(number).lower())
    try:
        dot_index = s_number.index(".")
    except ValueError:
        return "1"
    after_dot = s_number[dot_index + 1 :]

    if not after_dot:
        return "1"

    return f"0.{'0' * (len(after_dot) - 1)}1"
Answered By: Dorian Turba
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.