How to extract the last digit of a number in python?

Question:

I have to make a function that does the division 1/7 and prints the digit n of the decimal expansion of 1/7.
The decimal expansion of 1/7 is a 6-digit repeating decimal with the digits 142857.

For example:

n = 2
Position 2 is 1[4]2857.
In other words, it should return 4.

What I did was first limit the expansion to position n and then extract the last number. In this way:

def truncate():
  num = 1/7 #0.14285714285714285
  cant_decimals = 2
  positions = pow(10.0, cant_decimals)
  return math.trunc(positions * num) / positions

truncate()

Here it returns 0.14, but I want it to return only 4 and I can’t think of how to do it, since I can’t use lists or strings, please help!

Asked By: Lina Sofia

||

Answers:

Use the decimal module for a better floating point arithmetic.

  1. Shift your digit just before the decimal point, by multiplying the whole number by 10 raised by the power of the decimal position of the digit itself (ex.: 0.14 -> 0.14*1E2 = 14.)
  2. divide that number by 10, the remainder is your digit
from decimal import Decimal, getcontext


def get_decimal_digit(number: Decimal, decimal_position: int) -> int:
    """ Get the digit after the decimal point, at decimal_position, in number """

    if decimal_position < 1:
        raise Exception("decimal_position < 1")

    number, decimal_position = Decimal(number), Decimal(decimal_position)
    getcontext().prec = 28  # set precision

    return int(number * Decimal(10) ** decimal_position) % 10
    

num = Decimal(1) / Decimal(7) # Decimal('0.1428571428571428571428571429')
get_decimal_digit(num, 2) # 4
Answered By: Jonathan Ciapetti
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.