Student Coder
Student Coder

Reputation: 11

How do I find the number in a specific decimal place?

For example, I want to get "8" from 1227.827 and "4" from 8.46 using the same code. Is this possible to do?

Upvotes: 0

Views: 169

Answers (3)

Frank
Frank

Reputation: 2029

It is not clear if you want to get the index of the occurences of the integer or the sum of occurences.

In both cases you need casting to string because a integer is one value while a string is an array of chars under the hood.

This finds the index of the first occurence of 8:

>>> get_index = lambda x, y: str(x).find(str(y))
>>> get_index(8.46, 4)
2
>>> get_index(1227.827, 8)
5

Upvotes: 0

Emil105
Emil105

Reputation: 158

For decimal places, use negative numbers

def nth_digit(x: float, n: int):
    x /= 10 ** n
    x %= 10
    return round(x - 0.5)


print(nth_digit(1227.827, -1))

Upvotes: 0

luk2302
luk2302

Reputation: 57114

Convert the number to a string, split it at the ., take the first character of the second split:

number = 1227.827 
int(str(number).split(".")[1][0])

8

Upvotes: 2

Related Questions