-1

I would like to know a way to calculate if a number is an integer or a double and to then put that into an if-else statement. Does anyone know how to?

  • Just to clarify some terminology: `Double` and `Int` are types. Regardless of their values, a `Double` is always a `Double`, and an `Int` is always an `Int`. A double can hold a value that so happens to be an integer (it's a whole number, divisible by 1 with no remainder), but an `Int` could never hold "a double" (a floating point value that can be non-integral) – Alexander Aug 29 '20 at 14:47

2 Answers2

1

You can write your own simple extension like:

extension FloatingPoint {
    var isInteger: Bool { rounded() == self }
}

usage:

2.0.isInteger // true
2.5.isInteger // false

Note that Double.infinity.isInteger and its negative are both return true as Alexander mentioned in comments.

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • 1
    Beware: `Double.infinity.isInteger` and `-Double.infinity.isInteger` both return true. – Alexander Aug 29 '20 at 14:44
  • 1
    @LeoDabus That's kind of a mess, a doubly nested conditional operators without a clear flow. the `isNormal` predicate is even negated, which makes it even trickier to read. The other two operands could have just been swapped in order, instead. This code is clever, and I fully understand how it works, but it takes way more effort to read/parse/understand than is necessary. I would suggest `!isNormal && (isZero || self == rounded())`, or better yet, breaking it down over 2 lines with a separate `if` statement. – Alexander Aug 29 '20 at 17:23
1

EDIT
You can write an extension function for Double:

extension Double {
  func isInteger() -> Bool {
    return self == floor(self)
  }
}

Original Answer
You can check by verifying if the number is the same when it's rounded down:

func isInteger(nr: Double) -> Bool{
  return nr == floor(nr)
}

Then you can use it like that:

if isInteger(3.5) {
  print("this is an integer")
}
mike
  • 68
  • 1
  • 4
  • Good idea, but I would recommend putting this in an extension on `Double`, instead. Also, omit the `( )` and add some spaces to the `if` predicate. – Alexander Aug 29 '20 at 14:45