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

Getting a floating point number input to print out as integer and a decimal

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:

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

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)

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