Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

  1. Make your digit the first one before the decimals, by multiplying it by 10 raised by the power of the decimal position of the digit itself
  2. then find the remainder of that number divided by 10, which is your digit
    num = 1/7 #0.14285714285714285

    def find_digit(number, decimal_position):
        if decimal_position < 1:
            raise Exception("decimal_position < 1")
        return int(number * 10 ** decimal_position) % 10

    find_digit(num, 2) # 4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading