I’m trying to ask a user to type in a floating point number. My program should then print it out as integer and a decimal. What I’m looking for is:
If user types : 1.34 … then integer should print: 1 and decimal should print: 0.34
Here’s what I’m doing:
number = float(input('Number: '))
print('integer: ', int(number))
print('decimal: ', number / 1))
I’m oblivious as to how do I round up to get exactly 0.34. If I should convert the number to float again in line 3 or divide the original number by 100 or something.
>Solution :
Just take the integer from the original float (assuming the number is positive)
number = float(input('Number: '))
print('integer: ', int(number))
print('decimal: ', number - int(number)))
Yes sometimes the result may be slightly inaccurate. This is a consequence of using floating point numbers here’s an explanation. As Eric pointed out rounding to several decimal places is a solution to this e.g. round(number - int(number), 10)