# Method `%()

Method `%

  ``mixed` `%(`object` `arg1`, `mixed` `arg2`)`
  ``mixed` `%(`mixed` `arg1`, `object` `arg2`)`
  ``string` `%(`string` `arg1`, `int` `arg2`)`
  ``array` `%(`array` `arg1`, `int` `arg2`)`
  ``float` `%(`float` `arg1`, `float`|`int` `arg2`)`
  ``float` `%(`int` `arg1`, `float` `arg2`)`
  ``int` `%(`int` `arg1`, `int` `arg2`)`

Description

  Modulo.

  Every expression with the `%` operator becomes a call to this function, i.e. `a%b` is the same as `predef::`%(a,b)`.

Returns

  If `arg1` is an object that implements lfun::`%() then that function will be called with `arg2` as the single argument.

  If `arg2` is an object that implements lfun::``%() then that function will be called with `arg2` as the single argument.

  Otherwise the result will be as follows:

  `arg1` can have any of the following types:

  ``string`|`array``

  If `arg2` is positive, the result will be the last ``%(<a class='ms reference' href='../predef_3A_3A/sizeof.html'>sizeof(<code class='reference paramref'>arg1`), <code class='reference paramref'>arg2) elements of `arg1`. If `arg2` is negative, the result will be the first ``%(<a class='ms reference' href='../predef_3A_3A/sizeof.html'>sizeof(<code class='reference paramref'>arg1`), -<code class='reference paramref'>arg2) elements of `arg1`.

  ``int`|`float`` | The result will be `<code class='reference paramref'>arg1` - <code class='reference paramref'>arg2*<a class='ms reference' href='../predef_3A_3A/floor.html'>floor(<code class='reference paramref'>arg1/<code class='reference paramref'>arg2). The result will be a float if either `arg1` or `arg2` is a float, and an int otherwise.

  For numbers, this means that

  1. `a % b` always has the same sign as `b` (typically `b` is positive; array size, rsa modulo, etc, and `a` varies a lot more than `b`).

  2. The function `f(x) = x % n` behaves in a sane way; as `x` increases, `f(x)` cycles through the values `0,1, ..., n-1, 0, ...`. Nothing strange happens when you cross zero.

  3. The `%` operator implements the binary "mod" operation, as defined by Donald Knuth (see the Art of Computer Programming, 1.2.4). It should be noted that Pike treats %-by-0 as an error rather than returning 0, though.

  4. `/` and `%` are compatible, so that `a == b*<a class='ms reference' href='../predef_3A_3A/floor.html'>floor(a/b) + a%b` for all `a` and `b`.

See also

  `/, floor()