Working with Numbers

Declaring and testing for numeric variables, performing arithmetic, and using various Math object methods for manipulating integers and floats, finding maximum and minimum values, and generating random numbers.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Declare numeric variables in JavaScript.
  • Use typeof and IsNaN() to test that a variable contains a number which can be used in calculations.
  • Perform addition, subtraction, multiplication, and division on numeric variables.
  • Use various methods of the Math object to manipulate positive and negative numbers, convert between integers and floats, find maximum and minimum values, and generate random numbers.

Working with Numbers: JS Code Snippets

Introducing numbers in JavaScript

Unlike other programming languages, JavaScript only has one number data type. This can store integers (positive or negative whole numbers) or floats (floating-point numbers with a decimal point).

Assigning numbers to variables

To assign a number to a variable, do not wrap the value in single or double quotes.

const myVar1 =   1234; // JavaScript treats myVar1 as a number
const myVar2 = "1234"; // JavaScript treats myVar2 as a string
const myVar3 = '1234'; // JavaScript treats myVar3 as a string

JavaScript decides which type of variable you want to create by the way that you first assign a value to it.

  • When you enclose the assigned value within quotes, JavaScript gives the variable a data type of string.
  • When you omit the quotes, JavaScript gives the variable a data type of number.

Here are two values that JavaScript will accept as valid numbers.

let Temperature = -6.3456 // Valid number 
let errorRare = .2727 // Valid number 

And here are two values that are not valid numbers in JavaScript.

let userIncome = 34,000; // Error. Contains a comma 
let product ID = 645w29; // Error. Contains a letter character 

In fact, they are not even valid variable assignments because JavaScript cannot understand what type of data type you want to create. Each line will throw an error.

The typof operator

If you are unsure about a variable’s data type, you can use the typeof operator on the variable as shown below.

let someVar;
// declare empty variable 
console.log(`Data type of someVar: ${typeof someVar}`);
// returns undefined  
someVar = "12";
console.log(`Data type of someVar: ${typeof someVar}`);
// returns string 
someVar = 12;
console.log(`Data type of someVar: ${typeof someVar}`);
// returns number 
someVar = "12";
console.log(`Data type of someVar: ${typeof someVar}`);
// returns string 

If the variable contains a number, typeof returns the string "number".

Testing for numbers with isNaN(n)

To test that a variable contains a number, another option is to use the global variable isNaN(n). NaN stands for 'Not a Number'. See below.

const stringVar = "Some text";
// declare string variable 
console.log(`Is this not a number ("Some text"): ${isNaN(stringVar)}`);
// returns true  
const numVar = 42;			
console.log(`Is this not a number ("42"): ${isNaN(numVar)}`);
// returns false  

Automatic variable type conversion is a powerful feature of JavaScript. But its very power can result in scripting errors or in scripts that produce unexpected results.

To check that a variable contains a number before using that variable in a calculation, you could test it in either of two ways as follows.

const varPossibleNumber = 2;
if (typeof varPossibleNumber === 'number') {
  // safe to continue with calculation
}
if (!isNaN(varPossibleNumber)) {
  // also safe to continue with calculation
}

Numbers that are never used in calculations can be correctly assigned to strings. For example, users’ telephone numbers. You will never want to divide a telephone number by two or deduct 10% from such a number.

let userTelNo = "088 123 456678"; // number as string

But never assign a number to a string variable if you intend using that number in a calculation.

Arithmetic operations

You can perform arithmetic with numeric variables using the arithmetic operators set out in the table below.

Operator

Operator Key Used

Description

x + y

The plus key

Adds the value of x and the value of y.

x - y

The dash key

Subtracts the value of y from the value of x.

x * y

The asterisk key

Multiplies the value of x by the value of y.

x / y

The forward slash key

Divides the value of x by the value of y.

See the simple examples below.

const firstNum = 12;
const secondNum = 8;
console.log(`Addition (12+8): ${12 + 8}`); // returns 20
console.log(`Subtraction (12-8): ${12 - 8}`); // returns 4
console.log(`Multiplication (12*8): ${12 * 8}`); // returns 96  
console.log(`Division (12/8): ${12 / 8}`); // returns 1.5

Operator precedence

JavaScript follows the rules of arithmetic when working with numeric variables and numbers:

  • Division first, followed by multiplication, then addition and finally subtraction.

For example, the following series of statements gives a result of 11 because JavaScript first multiplies 2 by 3 (resulting in 6) and then adds 5.

console.log(`5 + 2 * 3: ${5 + 2 * 3}`); // returns 11 

You can force JavaScript to perform calculations in a particular order by using parentheses ().

For example, the following calculation gives a result of 21. JavaScript first adds 5 and 2, because they are within (). And only then multiplies that result by 3 to give 21.

console.log(`(5 + 2) * 3: ${(5 + 2) * 3}`); // returns 21 

For example,

function convertToFahrenheit(celsius) {
   varFahrenheit = ((9/5) * celsius) + 32;
   console.log(`${celsius} Celsius:  = ${varFahrenheit} Fahrenheit`);
}

convertToFahrenheit(20);

Increment and decrement operators

JavaScript supports increment ++ and decrement -- prefix operators that increase or reduce the numerical value of a variable by one. They cannot be applied to literal values; only to numeric variables.

See the sample code below.

let myNum1 = 7;
let myNum2 = 24; 	
console.log(`myNum1 is 7`); 
console.log(`Increment operator (++myNum1) is ${++myNum1}`);
// returns 8
console.log(`myNum2 is 24`); 
console.log(`Decrement operator (--myNum2) is ${--myNum2}`);
// returns 23

The Math object

The JavaScript Math object offers lots of methods and properties for working with numbers. For example, rounding numbers, finding minimum and maximum values, and generating random numbers.

Syntax of the Math object

Unlike Date, another a built-in JavaScript object, the Math object is not a constructor and does not require the New keyword. Each Math object you use is automatically created by the JavaScript interpreter.

Below are some examples of code that uses the Math object.

${Math.round(9.75)}; // returns 10
${Math.max(1, 2, 3)};  // returns 3

Positive and negative numbers

JavaScript offers two methods for working with positive and negative numbers.

Math.abs(n)

Returns the absolute value of n.

Math.sign(n)

Returns 1 if n is positive, -1 if negative, or 0 if zero.

You can see some sample code below.

console.log(`Positive or negative number (19.99)? ${Math.sign(19.99)}`);
// returns 1
console.log(`Positive or negative number (-5)? ${Math.sign(-5)}`);
// returns -1
console.log(`Positive or negative number (0)? ${Math.sign(0)}`);
// returns 0

Integers and floats

Here are two common methods for working with integers and floats (floating-point numbers or decimals).

Math.round(n)

Returns the value of n rounded (up or down) to the nearest integer.

For example, 6.25 is rounded down to 6 and 7.75 becomes 8.

If n is a negative number, the return value is rounded upwards towards zero. -8.25 becomes -8.

Math.trunc(n)

Returns only the integer part of n.

All numbers after the decimal point . are discarded. No rounding is performed.

For example, 3.14159 simply returns 3.

Two related methods are the following.

Math.ceil(n)

Rounds n up to the next largest integer.

For example, 3.5 becomes 4, -5.7 becomes -5 (because -5 is greater than -6).

Math.floor(n)

Returns the largest integer less than or equal to n.

For example, 3.5 becomes 3, -5.7 becomes -6 (because -6 is lesser than -5).

You can see some sample code below.

console.log(Math.ceil(.95));    // returns 1
console.log(Math.ceil(4));      // returns 4
console.log(Math.ceil(7.004));  // returns 8
console.log(Math.ceil(-7.004)); // returns -7
console.log(Math.floor(45.95));  // returns 45
console.log(Math.floor(45.05));  // returns 45
console.log(Math.floor(4));      // returns 4
console.log(Math.floor(-45.05)); // returns -46
console.log(Math.floor(-45.95)); // returns -46

Note the difference between these two methods and Math.round(n):

  • Math.ceil(n): Rounds n upward towards the next integer value.   So 5.01 becomes 6 and 14.275 becomes 15.
  • Math.floor(n): Rounds n downward towards the next smallest integer value.   So 5.99 becomes 5 and 14.9999 becomes 14.
  • Math.round(n): Rounds n upward or downward to the nearest integer.   So 5.25 becomes 5 and 14.75 becomes 15.

These two methods are commonly used to transform the output of the Math.random() method from floats to more usable integer values.

Maximum and minimum values

For when you want to find the largest or smallest number in a range of numeric values, use one of the following methods.

Math.max(x,y,z)

Returns the highest number in a supplied range numeric parameters.

Math.min(x,y,z)

Returns the lowest number in a supplied range numeric parameters.

Here are some code samples.

console.log(Math.max(1, 2, 3));    // returns 3
console.log(Math.max(-1, -2, -3)); // returns: -1
console.log(Math.min(1, 2, 3));    // returns 1
console.log(Math.min(-1, -2, -3)); // returns -3

Generating random numbers

For when you want to generate a random value for a numeric variable, JavaScript offers the method below.

Math.random()

Returns a pseudo-random floating-point number in the range from 0 inclusive up to but not including 1.

Here is the code in its simplest form.

console.log(Math.random()); // returns a number from 0 to less than 1

Typcially, you will want your random number to be an integer rather than a floot. A simple solution is to:

  • Use the Math.floor() method to find the largest integer less than or equal to randomly-generated float.
  • Multply the output of the Math.floor() method by your choosen integer.

See the examples below.

console.log(Math.floor(Math.random() * 3)); 
// returns 0, 1 or 2 (never 3)
console.log(Math.floor(Math.random() * 6));
// returns 0, 1, 2, 4 or 5 (never 6)  

If you want a random integer between zero and one less than some supplied integer max, you could use the following solution:

// Function to generate random integer one less than supplied parameter
function getRandomIntUpper(max) {
   return Math.floor(Math.random() * max);
}
                 
console.log(getRandomIntUpper(5)); // returns: 0, 1, 2, 3 or 4
console.log(getRandomIntUpper(6)); // returns 0, 1, 2, 4 or 5 

The function below accepts as parameters two integers that will specify the smallest and largest possible random output inclusively.

// Generate random integer between supplied range inclusively
function getRandomInt(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min + 1) + min); 
}

// Both the min and max arguments are inclusive
console.log(getRandomInt(1, 9));  // returns 1, 2, 3, 4, 5, 6, 7, 8 or 9
console.log(getRandomInt(20, 24));// returns 20, 21, 22, 23 or 24