Previous Example-|-Next Example-|-Return to Chapter Listing

Example 5.5:
Modulus: Remainder after Dividing

Oops; we made a mistake when describing modulus. There's many a slip twixt programmer and writer, said Robert Burton (or something like that), and unfortunately this slip didn't get fixed before printing. The correct information will be included when the books are reprinted, but for those of you working from an earlier printing, here's the correct information:

The modulus operator (%) is, in effect, a shortcut for several steps you could carry out using other JavaScript operators. It's used to show what's left over once you divide one number into another, when the second number won't divide equally. For instance, divide 5 into 17, and what's left over?: 2. The number 5 divides into 17 three times (5 x 3 = 15). So what's left over? 17 - 15 = 2. This can be calculated like this: 17 % 5.

Click the following button to see the value in the nRoughPrice variable, the result of 1500 % 40:
1500/40 = 37.5
37 * 40 = 1480
1500 - 1480 = 20

This is the script we used. First we placed this in the HEAD: <SCRIPT LANGUAGE="JAVASCRIPT"> <!-- var nRoughPrice = 0 var nTotalCost = 1500 var nPeople = 40 nRoughPrice = nTotalCost % nPeople //--> </SCRIPT> Then we created this button: <form> <input type="button" name="VariableButton" value="The result of the calculation" onclick="alert(nRoughPrice)"> </form>
Previous Example-|-Next Example-|-Return to Chapter Listing