'First digit after the decimal of a randomly generated number
I am new to coding in Python, and I am struggling with a code that is supposed to give me the first digit after the decimal of a randomly generated number. So for example:
Input: 1.79 Output: 7
I currently have a code that partially works, but whenever a number has no decimal, for example 10, I want the code to give 0 as output, but I can't get it to work. My code:
''''decimal_number = (number - int (number))
print (str (decimal_number) [2])'''
It gives me the following error message when I try to input a number that has no decimals:
"Exception IndexError was raised but not expected: string index out of range"
Solution 1:[1]
input_data = '1.79'
n = float(input_data) # convert to float
second_digit = int(10 * n) % 10
print(second_digit)
#>>> 7
s = str(second_digit) # convert back to string, if necessary
print(s)
#>>> '7'
for input_data = '18', the output is '0'
Solution 2:[2]
input_data = '1.79'
if '.' in input_data:
input_data = input_data.split('.')
print(input_data[1][0])
elif '.' not in input_data:
print(input_data[1])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bodzio528 |
| Solution 2 | Captain Caveman |
