Andreas Sandberg - 1 year ago 77

Python Question

i'm making a program which divides a lot of numbers and I want to check if the number gets decimals or not. I also want it to print those decimals. Example:

`foo = 7/3`

if foo has a 3 in the decimals: (Just an example of what I want to do there)

print("It works!)

elif foo has no decimals: (another example)

print("it has no decimals")

EDIT: Ok, so since "check which decimal is afterwards" brought some confusion, let me explain. I want to be able to check IF a number has decimals. For example, 7/3 (foo) gives me decimals, but I want python to tell me that without me having to do the math. forget the "which decimal" part

Answer Source

If you just want to test whether a division has decimals, just check the modulo:

```
foo = a % b
if foo != 0:
# Then foo contains decimals
pass
if foo == 0:
# Then foo does NOT contain decimals
pass
```

However (since your question is a bit unclear) if you want to split the integer and decimal parts then use `math.modf()`

function:

```
import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)
```