-2

I'm having a hard time doing this I have tried experimenting with (0:.2f) I want the program to only print the decimal part Example inputs and outputs

Inputs 100.56 455.345 89.5

Outputs .56 .345 .5

Is there a way to do this?

3 Answers3

0

you may try the code as below

input = 100.56
print(input % 1)

you could refer to the answer at How to get numbers after decimal point?

Ramieeee
  • 1
  • 1
0

If you want to have only the original decimal part, you can do :

inputFloat = 25189456.1584566
decimalPart = '.' + str(inputFloat).split('.')[1]
print(decimalPart)
0

Something like this should work

def f(x, decimals=2):
    r = str(round(x, decimals)) #round and convert to string
    r = r.split('.')[-1] #split at the dot and keep the decimals
    r = '.' + r #add the dot
    return r

f(100.56789) #.57

[f(x) for x in [100.56, 455.345, 89.5]] #['.56', '.35', '.5']

The one-liner would be '.' + str(round(x, 2)).split('.')[-1] or f".{str(round(x, 2)).split('.')[-1]}" where x is the float you are interested in.

alec_djinn
  • 10,104
  • 8
  • 46
  • 71