The `%` operator yields the remainder after dividing the left operand by the right. This is otherwise known as the modulo or modulus operator.

In an ECMAScript compliant interpreter, the remainder is a floating-point value and, unlike the C and C++ languages, the input operands can also be floating point values.

The result of performing a remainder on floating point values is not the same as the IEEE 754 remainder operation. IEEE 754 mandates a remainder computed via a rounding division whereas ECMA mandates a truncating remainder. In ECMAScript the remainder behaves similarly to the Java integer remainder operator and is analogous to the `fmod()` library function in C language compilers.

The behavior in an ECMA complaint JavaScript implementation should obey these rules:

If either operand is

`NaN`then the result is`NaN`.The sign of the result is the same as the sign of the dividend (the operand on the left).

If the dividend is an infinity, the result is

`NaN`.If the divisor is zero, the result is

`NaN`.If the dividend is a finite value and the divisor is infinity, the result equals the dividend.

If the dividend is zero and the divisor is finite, the result is zero.

Otherwise, as long as neither an infinity, zero or `NaN` is involved, the floating remainder is calculated like this. The dividend `n` is divided by the divisor `d` to produce a quotient, `q`. The quotient is forced to be an integer and multiplied again by `d` and the result subtracted from `n` to yield the remainder. Thus:

`q = n/d`

`r = n - (d * q)`

The value `q` will be forced to be an integer although the resulting value `r` may not be.

The associativity is left to right.

Refer to the operator precedence topic for details of execution order.

JScript version 1.0 truncates floating-point values to integers before applying the remainder operator. This means that the expression

`5.5 % 2.2`yields the value`1`.

ECMA 262 edition 2 - section - 11.5.3

ECMA 262 edition 2 - section - 11.13

ECMA 262 edition 3 - section - 11.5.3

Wrox Instant JavaScript - page - 19

Prev | Home | Next |

releaseEvents() | Up | Remainder then assign (%=) |

JavaScript Programmer's Reference, Cliff WoottonWrox Press (www.wrox.com)Join the Wrox JavaScript forum at p2p.wrox.comPlease report problems to support@wrox.com© 2001 Wrox Press. All Rights Reserved. Terms and conditions. |