Search code examples
swiftmodulusnegative-number

Swift Double.remainder(dividingBy:) returning negative value


let num = 32.0
Double(num).remainder(dividingBy: 12.0)

I'm getting -4?..instead of 8.0...it's subtracting 12.0 from 8.0

how do i fix this?


Solution

  • Please, read the documentation carefully:

    For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.

    (emphasis mine)

    You want to use truncatingRemainder(dividingBy:) instead:

    let num = 32.0
    let value = Double(num)
        .truncatingRemainder(dividingBy: 12)
    print(value) // 8