How to get the first digit after the decimal point of a float number in Python

1 Answer

0 votes
import math

#
# first_digit_after_decimal:
# --------------------------
# Extracts the first digit after the decimal point from a float.
#
# Method:
# 1. Use math.modf() to split the number into fractional and integer parts.
# 2. Convert the fractional part to a string.
# 3. Index the character immediately after "0." to obtain the first digit.
#
# This approach is simple, clear, and avoids unnecessary conversions.
#
def first_digit_after_decimal(value: float) -> int:
    fractional, _ = math.modf(abs(value))   # isolate fractional part
    s = str(fractional)                     # convert to string
  
    return int(s[2])                        # character after "0."

#
# Example usage
#
f = 234.872
digit = first_digit_after_decimal(f)

print(digit)


'''
run:

8

'''

 



answered Aug 29, 2019 by avibootz
edited Sep 15 by avibootz

Related questions

...