Mono.WTF - 9 months ago 57

iOS Question

How can i check if a number is decimal or not using swift?

With Objective-C:

`if (number == (int) number) {`

//decimal

}

else {

//not decimal

}

Answer Source

If you round the number down (which you can do by using the floor function), and then subtract it from the original number, you will get the difference between the two.

```
if (number - floor(number) > 0.000001) { // 0.000001 can be changed depending on the level of precision you need
// decimal
}
```

Edit --

My original answer recommended calculating the difference between the number and its floored equivalent to see if there were any units after the decimal points. However, as later described, there may be a rounding error which causes the representation of a value in memory to be slightly different than what it's actually meant to be.

For example, 3.0 could be represented as 3.00000000000001, and therefore the `number - floor(number) > 0`

would return true, even though it should've theoretically returned false as the offset would be 0.00000000000001.

**Therefore please use @jessy's answer below.**