Swift\'s substitutes for the % symbol for floating point numbers:
func truncatingRemainder(dividingBy other: Self) -> Self
truncatingRemainder computes the remainder of the "truncating division", and remainder computes the remainder of the "rounding division".
Example (from the API reference):
let x = 8.625
let y = 0.75
Truncating division and remainder:
let q1 = (x/y).rounded(.towardZero)
let r1 = x.truncatingRemainder(dividingBy: y)
print(q1, r1) // 11.0 0.375
print(q1 * y + r1) // 8.625
Rounding division and remainder:
let q2 = (x/y).rounded(.toNearestOrEven)
let r2 = x.remainder(dividingBy: y)
print(q2, r2) // 12.0 -0.375
print(q2 * y + r2) // 8.625
So in any case, the remainder rem
of a division x
by y
is
rem = x - quot * y
where quot
is "a rounded quotient" of the division x
by y
.
For truncatingRemainder
, quot
is the quotient
rounded towards zero, and for remainder
, quot
is the quotient
rounded towards the nearest integer.
The result of truncatingRemainder
has always the same sign
as the dividend, this need not be the case for remainder
.
If both x
and y
are exactly representable as an integer
then the result of
x.truncatingRemainder(dividingBy: y)
is the same as
Int(x) % Int(y)
with the integer remainder operator %
.