191k views
0 votes
2.4 Code Practice: Question 2

Write a program that accepts a number as input, and prints just the decimal portion. Your program should also work if a negative number is inputted by the user.

Enter a number: 15.789
Sample Output
0.789

Can someone please help me with this because I’m so stuck

1 Answer

3 votes

Final answer:

To obtain just the decimal portion of a number in a program, subtract the integer part from the number and use the absolute value function to ensure the result is positive, even when a negative number is input.

Step-by-step explanation:

Extracting the Decimal Portion of a Number

To write a program that prints just the decimal portion of any number entered by a user, you need to separate the decimal part from the integer part of the number. This can be done by subtracting the integer value of the number from the original number itself, which effectively removes the integer part and leaves you with only the decimal portion. Here is an example in Python:

number = float(input('Enter a number: '))
decimal_portion = number - int(number)
print('Sample Output')
print(abs(decimal_portion))
Note that we use the abs() function to ensure that the output is positive, as the question specifies that the program should also work with negative numbers.
User Chris Holwerda
by
4.6k points