How to get the Nth digit after the decimal point of a floating-point number in Python

1 Answer

0 votes
def get_nth_decimal_digit(value: float, position: int) -> int:
    """
    Return the Nth digit after the decimal point.

    Examples:
        get_nth_decimal_digit(123.456789, 1) -> 4
        get_nth_decimal_digit(123.456789, 2) -> 5
        get_nth_decimal_digit(123.456789, 3) -> 6

    Args:
        value: The floating-point number to inspect.
        position: The digit position after the decimal point (1-based).

    Returns:
        The requested digit (0-9).

    Raises:
        ValueError: If position is less than 1.
    """
    if position < 1:
        raise ValueError("position must be a positive integer")

    # Convert to a positive value.
    value = abs(value)

    # Convert the number to a string with a fixed precision.
    number_str = f"{value:.15f}"

    # Find the decimal point.
    decimal_pos = number_str.find(".")

    if decimal_pos == -1:
        return 0

    # Calculate the position of the requested digit.
    digit_index = decimal_pos + position

    # Return 0 if the digit does not exist.
    if digit_index >= len(number_str):
        return 0

    return int(number_str[digit_index])


def main() -> None:
    """Program entry point."""

    number: float = 123.456789

    print(f"Number: {number}")
    print()

    for position in range(1, 7):
        digit = get_nth_decimal_digit(number, position)
        print(f"{position} digit after decimal = {digit}")

    print("\nAdditional Examples")
    print("-------------------")

    print(
        f"123.456789, position 4 -> "
        f"{get_nth_decimal_digit(123.456789, 4)}"
    )

    print(
        f"-98.7654, position 2 -> "
        f"{get_nth_decimal_digit(-98.7654, 2)}"
    )

    print(
        f"1.2, position 5 -> "
        f"{get_nth_decimal_digit(1.2, 5)}"
    )


if __name__ == "__main__":
    main()


'''
run:

Number: 123.456789

1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9

Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0

'''

 



answered Oct 15 by avibootz

Related questions

...