The first new concept to introduce to you is that of variables. A variable is a string (a collection of letters and possibly numbers, but must start with a letter to hold a value for you. Think back to learning algebra at school and you might see something like this:
x holds the result of 3 + 4.
y holds the value of 1 + 1.
z holds the value of x + y, making the value of
As simple as this example is
x, y, z are variables. On their own they are meaningless but once you give them a value they mean something and can be used for calculations.
Strings Are Not Numbers
Before we dive into more code, there is an important thing to stress here: a string is not a number. A string, remember is a collection of words and numbers. Here’s a demo to explain what I mean:
By surrounding a number with speechmarks, the number is interpreted as a string. This is different to other programming languages. PHP quite happily knows that
"1" + "2" = "12".
The reason this is important is that taking numbers from form elements usually are seen as strings. Fields such as
- SELECT drop-down options
- Tick Box Values
- Text Boxes / Text Areas
All rely on strings. This means we need to make sure that the strings are converted to numbers.
Converting Strings to Numbers
I will introduce you to two different kinds of numbers here: integers and floats. An integer is a whole number (whether positive or negative). A float contains decimal points.
Convert a String into a Whole Number
parseInt function, as follows:
Note that this is not a rounding function. So if you change the second value to
parseInt() function will still return 40.
Convert String to a Float
If your string value has decimal places in them and you want to retain those decimal places then you should use
parseFloat() instead of
Converting Form Fields to Numbers
In the examples below we will be combining functions to grab the values from two drop-down boxes and convert them to an integer before performing mathematical functions on them. Let’s built this together, so first let’s make our form fields.
So here we:
- Created two SELECT boxes and gave them each a unique ID
- Created an empty
<p>and gave it and ID. We will use this to output the result of our functions.
- Created a button for each of the mathematical functions we will look at
But remember, the drop-down boxes send the numbers as strings! So we need to take the value selected and push it through the
As with our examples of
y earlier, we have set up variables
number2. We grab the selected option and convert it to a whole number. A discussion of Arrays will be a future lesson, but you’ll notice that here we have not use the
this.options[this.selectedIndex] from the last lesson. This is because we are not inside the object, so we have to grab it remotely using
Only once our selected options are numbers, can we perform mathematical functions on them.
We will first output when the two numbers are added together. Set up a function called
Addition(). Scroll to ‘
The first two lines inside the function we will repeat for most functions in this tutorial. We take the two dropdown boxes and put them into variables
number2. Although there’s strictly no need to do it, for clarity we have created a new variable called
Unlike, say a text box, a paragraph doesn’t have a HTML
value you can write to. Instead we are forced to dynamically rewrite the HTML inside that paragraph. We can do this with
document.getElementById('ID NAME').innerHTML. So for all our mathematical functions, we will be rewriting the
innerHTML value of the paragraph, which we have given the ID of
Once you have your numbers, addition is the same as ‘normal’ maths – you just use the
+ operator. Note however that
+ is used to both add numbers and to add strings together. So
output = number1 + number2;
document.getElementById('playingWithMaths').innerHTML = 'Result: '+output;
The first line here is a mathematical function, but
'Result: '+output creates a string which joins the word ‘Result: ‘ to the actual outcome of
number1 + number2.
As with ‘normal’ maths, you can subtract numbers using
- (which is a normal hyphen). Be careful you don’t use what is called an ‘Em Dash’. If you use a hyphen in word processors, such as Microsoft Word, it will convert it to a ‘long dash’. This is not a valid substract. If you’re using a code editor or a simple notepad you should be fine. So our new
Subtract() function looks something like this:
To multiply two numbers, we can’t use
x because that’s a string! And we can’t use
× because that’s a HTML special character.
To be able to multiply you instead have to use
* (the asterisk which may be above the number 8 on your keyboard). So this is our
Multiply() function (scroll to
/ operator. Now, I want to hit a couple of other issues here, because division gives rise to fractions. Take the simple sum of
10 / 3 = 3.333333. That is the result of there being three 3’s and remainder 1, which is ⅓ (or 0.333333 – recurring ad infinitum).
Rounding Your Results
Math.round(): this will round your number up or down depending on how much your fraction is. So 0.4 will be rounded down to 0, but 0.5 will be rounded up to 1.
Math.floor(): this will round down your fraction, regardless of how much is left. So 0.4 will be rounded down to 0. 0.5 will also be rounded down to 0.
Math.ceil(): like ‘ceiling’ it rounds up regardless of how much is after the decimal point. So 0.4 will be rounded up to 1. 0.5 will also be rounded up to 1.
Rounding With Decimal Places
The functions above will round to whole numbers but you may want to round to a certain number of decimal places. In this case you can use the following function:
yourVariableName.toFixed(x); function, where
x is the number of decimal places. It effectively, most of the time uses the same principle as
Math.round() but with fractions of numbers rather than whole numbers.
So here’s a function which takes your drop-down boxes and converts the division to 2 decimal places. Note:
toFixed() enforces the two decimal places even if they are not needed. So if your division result is a whole number, you’ll still get
.00 on the end:
Division: Getting the ‘Remainder’ Value
If you remember back to school when you did division sums, often you would be asked to divide one number by another and then say what the remainder is. By that I mean 10 divided by 3 = 3 remainder 1.
% operator. Don’t get confused this is not a percentage, in this situation! This means if you do
x = 10 % 3, the answer you will get is 1. We can combine this with a normal division, to be able to output the 10 divided by 3 = 3 remainder 1 by rounding down
Maths.floor() as follows (Scroll to
Simple Dice Rolling Function
Let’s say you want to create a game to roll two dice. To keep it simple I mean 6-sided dice, rather than the 12-sided dies used in many modern games. We will be using multiplication and addition for this exercise. We will also be rounding using
Math.floor() so will combine a few things learned in this module.
Random Number Generation
Math.random(). However, this function generates a random decimal between 0 and 1. Because dice have six sides (of which side ‘zero’ is non-existent!) we need to generate a random number between 1 and 6.
To create a random number within a certain range of numbers, we need to combine
Math.floor() to get whole numbers.
dice1 = Math.floor((Math.random()*highest_number)+lowest_number);
You can see I have used two variables
lowest_number. This will allow you to use 12-sided dice if you want to, or any other number of ‘sides’ for that matter.
BODMAS Applies Here
So if you want something done first surround it in
dice1 code above, they are processed in this order:
- Round down (via
Math.floor) the result of 1 and 2.
- Assign the rounded value to
The Dice Rolling Script
Putting together all we have learned we can now create our dice rolling script and output it to a paragraph tag using
innerHTML. Here it is:
Maths governs a lot in programming – especially when creating interactive features such as games or dynamic layouts. In this lesson you have learned to perform simple mathematical functions, round numbers and generate random numbers between predefined start and end points.
The companion demo script can be downloaded from here. Take it and play with it to help you solidify what you have learned here!