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

Time:05-31

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.

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

  • Related