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

Question:

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.

Asked By: Ron

||

Answers:

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)

Answered By: Jacob

dividing is clearly not the perfect solution to do that, you can use the function round as follows:

number = str(round(float(input('Number: ')), 2))
integer, dec = number.split('.')

print(f'integer: {integer}, decimal: 0.{dec}')

output:

Number: 1.2658
integer: 1, decimal: 0.27
Answered By: mrCopiCat

Consider the following:

i,d=map(int, number.split('.') if '.' in number else [number, '0'])

Covers whole numbers without forcing user to input 1.0

Answered By: Jacek BÅ‚ocki

this is another way to get 2 decimal places

 number = float(input('Number: '))
    print('integer: ', int(number))
    dec= number - int(number)
    print('decimal: ', round(dec,2))
    
    Number: 1.34
    integer:  1
    decimal:  0.34
Answered By: Kayone
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.