JS Numbers

Welcome to another tutorial, here you will learn how to represent numbers in JavaScript.

Let’s start with working with numbers.

 

Working with Numbers

When dealing with numbers in programming, we have integer and floating-point numbers. JavaScript also supports floating-point numbers and integers, and they can be represented in octal notation, decimals, hexadecimal, etc. JavaScript is known for not treating integer and floating-point numbers differently. Hence, all numbers in JavaScript are represented by floating-point numbers. This is shown in the example below.

Example:

var x = 2;  // integer number
var y = 3.14;  // floating-point number
var z = 0xff;  // hexadecimal number

Extra large numbers can be represented in exponential notation e.g. 6.02e+23 (same as 6.02x1023).

var x = 1.57e4;  // same as 15700
var y = 4.25e+6;  // same as 4.25e6 or 4250000
var z = 4.25e-6;  // same as 0.00000425

Tip: In JavaScript, the biggest safe integer is 9007199254740991 ( i.e. 253-1), and the smallest safe integer is ‘-9007199254740991 (i.e. -(253-1)).’

Hexadecimal notation (or base 16) are numbers that are commonly used to represent colors. They have the prefixed '0x'. This is shown in the example below.

var x = 0xff;  // same as 255
var y = 0xb4;  // same as 180
var z = 0x00;  // same as 0

Note: Exponential notation or decimal are used to represent float-point numbers, while decimal, hexadecimal, and octal notation are used to represent integers.

 

Operating on Numbers and Strings

From one of our previous tutorials, you learned that the + operator is used for both addition and concatenation operations. So, carrying out mathematical operations on numbers and strings may produce interesting results. The use of the operator makes mathematical operations on numbers and strings interesting as it produces reasonable results. This is shown in the example below.

Example:

<html>
<head></head>
<body>
  <script>
var x = 10;
var y = 20;
var z = "30";

// Adding a number with a number, the result will be sum of numbers
document.write("<br>" + x + y); // 30

// Adding a string with a string, the result will be string concatenation
document.write("<br>" + z + z); // '3030'

// Adding a number with a string, the result will be string concatenation
document.write("<br>" + x + z); // '1030'

// Adding a string with a number, the result will be string concatenation
document.write("<br>" + z + x); // '3010'

// Adding strings and numbers, the result will be string concatenation
document.write("<br>" +"The result is: " + x + y); // 'The result is: 1020'

// Adding numbers and strings, calculation performed from left to right
document.write("<br>" + x + y + z); // 'The result is: 3030'
  </script>
</body>
</html>

Try with example

From the example above, operators with the same precedence are evaluated from left to right, therefore making the operation a none simple string concatenation. This is because the variables x and y are assigned numbers, hence, they are added first then the result is concatenated with the variable z which is a string.

However, in operations like division, subtraction, and multiplication the result will be different. Hence, JavaScript automatically converts numeric stings (meaning strings containing numeric values) to numbers in all numeric mathematical operations. Let's take a look at the example below.

Example:

var x = 10;
var y = 20;
var z = "30";

// Subtracting a number from a number
console.log(y - x); // 10

// Subtracting a number from a numeric string
console.log(z - x); // 20

// Multiplying a number with a numeric string
console.log(x * z); // 300

// Dividing a number with a numeric string
console.log(z / x); // 3

Note: when you attempt to multiply or divide numbers with strings that are not numeric, it returns NaN ( I.e. Not a Number). More so, when you use NaN in a mathematical operation, it will return ‘NaN’.

var x = 10;
var y = "foo";
var z = NaN;

// Subtracting a number from a non-numeric string
console.log(y - x); // NaN

// Multiplying a number with a non-numeric string
console.log(x * y); // NaN

// Dividing a number with a non-numeric string
console.log(x / y); // NaN

// Adding NaN to a number 
console.log(x + z); // NaN
						
// Adding NaN to a string 
console.log(y + z); // fooNaN


Representing Infinity

When we talk about infinity, we are talking about numbers that are too big for JavaScript to handle. But, JavaScript has a special keyword for positive infinity ( + infinity) and negative infinity ( - infinity). For instance, dividing by 0 returns infinity, let’s see it clearly in the example below.
Example:

var x = 5 / 0;
console.log(x); // Infinity

var y = -5 / 0;
console.log(y); // -Infinity

Note:  Infinity is a special value that is greater than any number and is represented by the mathematical Infinity ‘∞’. 

 

Avoiding Precision Problems

Most times when carrying out mathematical operations on floating–point numbers, unexpected result is usually produced. This is shown below:

Example:

var x = 0.1 + 0.2;
console.log(x) // 0.30000000000000004

We can see that the result obtained is 0.30000000000000004 instead of the expected 0.3. So in JavaScript, this difference is called ‘representation error or roundoff error’ and occurs because JavaScript and many other languages use binary (I.e. base 2) form to represent decimal (i.e. base 10). however, most decimal fractions can't be represented exactly in binary form, so few differences occur.

In other to avoid this difficulty we can use the solution something like this:

Example:

var x = (0.1 * 10 + 0.2 * 10) / 10;
console.log(x) // 0.3

 

Floating-point numbers are rounded to 17 digits in JavaScript, this helps in increasing precision and accuracy. But, the case of integers ( i.e numbers without fraction parts or exponential notation) is rounded up to 15 digits in JavaScript for accuracy. Let's see this in action in the example below.

Example:

var x = 999999999999999;
console.log(x); // 999999999999999

var y = 9999999999999999;
console.log(y); // 10000000000000000


Performing Operations on Numbers

From our previous topics, you are informed that in JavaScript that data types can be in the form of objects, especially when you make reference to them with the property access notation i.e the ‘dot notation’. Hence, JavaScript makes it possible for several properties and methods to be used for number values operations.

In the subsequent sections of this tutorial, you will be introduced to the number of methods commonly used. 


Parsing Integers from Strings

In JavaScript, we use the parseInt() method to parse an integer from a string. The parseInt() method is very important in cases where you are dealing with values like the CSS units ( e.g 50px, 12pt). also, if you want to extract the numeric value from it.

The parseInt() method is so unique that when it comes across a character that is not numeric in its specified base, it will stop parsing and returns the integer value of the previous step before that particular point. Hence, if a character cannot be converted into a number ( the first character), the parseInt() will return NaN and not a number. However, leading and trailing spaces are permitted. Below is an example:

 

Example:

console.log(parseInt("3.14"));  // 3
console.log(parseInt("50px"));  // 50
console.log(parseInt("12pt"));  // 12
console.log(parseInt("0xFF", 16));  // 255
console.log(parseInt("20 years"));  // 20
console.log(parseInt("Year 2048"));  // NaN
console.log(parseInt("10 12 2018"));  // 10

Note: The parseInt() method truncates numbers to integer values. However, it can not be used in place of the ‘Math.floor()’ method.

More so, the parsefloat() method can be used to parse floating-point numbers from a string. This method works just like the parsInt() method, but it retrieves both integers and numbers with decimals.

Example:

console.log(parseFloat("3.14"));  // 3.14
console.log(parseFloat("50px"));  // 50
console.log(parseFloat("1.6em"));  // 1.6
console.log(parseFloat("124.5 lbs"));  // 124.5
console.log(parseFloat("weight 124.5 lbs"));  // NaN
console.log(parseFloat("6.5 acres"));  // 6.5


Converting Numbers to Strings

In converting numbers to strings, the toString() method can be used. The method optionally accepts an integer parameter usually in the range of 2 to 36 and by specifying the base for representing numeric values. Below is an example.

Example:

var x = 10;
var y = x.toString();
console.log(y);  // '10'
console.log(typeof y);  // string
console.log(typeof x);  // number

console.log((12).toString());  // '12'
console.log((15.6).toString());  // '15.6'
console.log((6).toString(2));  // '110'
console.log((255).toString(16));  // 'ff'


Formatting Numbers in Exponential Notation

Formatting numbers in exponential notation can be done with the ‘toExponential()’ method. It optionally accepts an integer parameter specifying the number of digits after the decimal point. However, the result is a string and not a number. This is an example.

var x = 67.1234;

console.log(x.toExponential());  // 6.71234e+1
console.log(x.toExponential(6));  // 6.712340e+1
console.log(x.toExponential(4));  // 6.7123e+1
console.log(x.toExponential(2));  // 6.71e+1

Note: To represent very large or very small numbers you can use exponential notation. For example, 62500000000 can be written as 625e+8 or 6.25e+10.

 

Formatting Numbers to Fixed Decimals

The ‘toFixed()’ method can be used when you want to format a number with a fixed number of digits usually to the right of the decimal point. This method has an exactly specified number of digits after the decimal point and the value returned is a string. The digits parameter is treated as 0 if it is not specified or omitted. Here's an example;

var x = 72.635;

console.log(x.toFixed());  // '73' (note rounding, no fractional part)
console.log(x.toFixed(2));  // '72.64' (note rounding)
console.log(x.toFixed(1));  // '72.6'

var y = 6.25e+5;
console.log(y.toFixed(2)); // '625000.00'

var z = 1.58e-4;
console.log(z.toFixed(2));  // '0.00' (since 1.58e-4 is equal to 0.000158)


Formatting Numbers with Precision

The toPrecision() method can be used to get the most appropriate form of a number. Through this method, a string representing the number to the specified precision is returned.

Fixed-point notation can be used to format numbers if the precision is large enough to include all the digits of the integer part of a number. Contrarily, the number is formatted using exponential notation. Here's an example:

Example:

var x = 6.235;

console.log(x.toPrecision());  // '6.235'
console.log(x.toPrecision(3));  // '6.24' (note rounding)
console.log(x.toPrecision(2));  // '6.2'
console.log(x.toPrecision(1));  // '6'

var y = 47.63;
console.log(y.toPrecision(2)); // '48' (note rounding, no fractional part)

var z = 1234.5;
console.log(z.toPrecision(2));  // '1.2e+3'


Finding the Largest and Smallest Possible Numbers

Several properties are associated with the Number object and they are:

  • The number.max_value
  • number.min_value

These Number object properties represent the largest and smallest (closest to zero, not most negative) possible positive numbers that JavaScript can handle. They are constants with the actual values of 1.7976931348623157e+308, and 5e-324, respectively.

number.positive_infinity or number.negative_infinity as a constant represents a number that falls outside of the range of possible numbers. Here's an example:

Example:

var a = Number.MAX_VALUE;
console.log(a); // 1.7976931348623157e+308

var b = Number.MIN_VALUE;
console.log(b); // 5e-324

var x = Number.MAX_VALUE * 2;
console.log(x); // Infinity

var y = -1 * Number.MAX_VALUE * 2;
console.log(y); // -Infinity