ios how to check if division remainder is integer

any of you knows how can I check if the division remainder is integer or zero?

if ( integer ( 3/2))

Answers


You should use the modulo operator like this

// a,b are ints
if ( a % b == 0) {
  // remainder 0
} else
{
  // b does not divide a evenly
}

It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.

3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1

However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:

//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
    //All non-integer values go here
}
else
{
    //All integer values go here
}

Walkthrough

(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true

swift 3:

if a.truncatingRemainder(dividingBy: b) == 0 {
    //All integer values go here
}else{
    //All non-integer values go here
}

You can use the below code to know which type of instance it is.

var val = 3/2
var integerType = Mirror(reflecting: val)

if integerType.subjectType == Int.self {
  print("Yes, the value is an integer")
}else{
  print("No, the value is not an integer")
}

let me know if the above was useful.


Swift 5

if numberOne.isMultiple(of: numberTwo) { ... }

Swift 4 or less

if numberOne % numberTwo == 0 { ... }

Swift 2.0

print(Int(Float(9) % Float(4)))   // result 1

Need Your Help

Get every n-elements of array

arrays ruby iteration enumeration

How to select every n-elements (e.g. six) of an array using Ruby 1.9+? Example:

Distinctive traits of the functional languages

haskell f# functional-programming erlang clojure

It is known that all functional languages share some basic properties like using functions as basic building block for programs with all the consequences like using recursion instead of iteration.