JavaScript Numbers

In this tutorial you will learn how to represent numbers in JavaScript.

Working with Numbers

JavaScript supports both integer and floating-point numbers that can be represented in decimal, hexadecimal or octal notation. Unlike other languages, JavaScript does not treat integer and floating-point numbers differently. All numbers in JavaScript are represented as floating-point numbers. Here's an example demonstrating the numbers in different formats:

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

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

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

Tip: The biggest safe integer in JavaScript is 9007199254740991 (253-1), whereas the smallest safe integer is -9007199254740991 (-(253-1)).

Numbers can also be represented in hexadecimal notation (base 16). Hexadecimal numbers are prefixed with 0x. They are commonly used to represent colors. Here's an example:

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

Note: Integers can be represented in decimal, hexadecimal, and octal notation. Floating-point numbers can be represented in decimal or exponential notation.

Operating on Numbers and Strings

As you know from the previous chapters, the + operator is used for both addition and concatenation. So, performing mathematical operations on numbers and strings may produce interesting results. The following example will show you what happens when you add numbers and strings:

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

// Adding a number with a number, the result will be sum of numbers
console.log(x + y); // 30

// Adding a string with a string, the result will be string concatenation
console.log(z + z); // '3030'

// Adding a number with a string, the result will be string concatenation
console.log(x + z); // '1030'

// Adding a string with a number, the result will be string concatenation
console.log(z + x); // '3010'

// Adding strings and numbers, the result will be string concatenation
console.log("The result is: " + x + y); // 'The result is: 1020'

// Adding numbers and strings, calculation performed from left to right
console.log(x + y + z); // 'The result is: 3030'

If you observe the above example carefully, you will find that the result of the last operation is not just a simple string concatenation, because operators with the same precedence are evaluated from left to right. That's why, since variables x and y both are numbers they are added first then the result is concatenated with the variable z which is a string, hence final result is 30 + "30" = "3030".

But, if you perform other mathematical operations like multiplication, division, or subtraction the result will be different. JavaScript will automatically convert numeric strings (i.e. strings containing numeric values) to numbers in all numeric operations, as shown in the following example:

let x = 10;
let y = 20;
let 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

Moreover, if you try to multiply or divide numbers with strings that are not numeric, it returns NaN (Not a Number). Also, if you use NaN in a mathematical operation, the result will also be NaN.

let x = 10;
let y = "foo";
let 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

Infinity represents a number too big for JavaScript to handle. JavaScript has special keyword Infinity and -Infinity to represent positive and negative infinity respectively. For example, dividing by 0 returns Infinity, as demonstrated below:

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

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

Note: Infinity is a special value that represents the mathematical Infinity , which is greater than any number. The typeof operator return number for an Infinity value.

Avoiding Precision Problems

Sometimes, operations on floating-point numbers produce unexpected results, as shown here:

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

As you can see the result is 0.30000000000000004 rather than the expected 0.3. This difference is called representation error or roundoff error. It occurs because JavaScript and many other languages uses binary (base 2) form to represent decimal (base 10) numbers internally. Unfortunately, most decimal fractions can't be represented exactly in binary form, so small differences occur.

To avoid this problem you can use the solution something like this:

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

JavaScript round floating-point numbers to 17 digits, which is enough precision or accuracy in most cases. Also, in JavaScript integers (numbers without fractional parts or exponential notation) are accurate is up to 15 digits, as demonstrated in the following example:

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

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

Performing Operations on Numbers

JavaScript provides several properties and methods to perform operations on number values. As you already know from the previous chapters, in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

In the following sections, we will look at the number methods that are most commonly used.

Parsing Integers from Strings

The parseInt() method can be used to parse an integer from a string. This method is particularly handy in situations when you are dealing with the values like CSS units e.g. 50px, 12pt, etc. and you would like to extract the numeric value out of it.

If the parseInt() method encounters a character that is not numeric in the specified base, it stops parsing and returns the integer value parsed up to that point. If the first character cannot be converted into a number, the method will return NaN (not a number).

Leading and trailing spaces are allowed. Here's an 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, but it should not be used as a substitute for Math.floor() method.

Similarly, you can use the parseFloat() method to parse floating-point number from a string. The parseFloat() method works the same way as the parseInt() method, except that it retrieves both integers and numbers with decimals.

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

The toString() method can be used to convert a number to its string equivalent. This method optionally accepts an integer parameter in the range 2 through 36 specifying the base to use for representing numeric values. Here's an example:

let x = 10;
let 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

You can use the toExponential() method to format or represent a number in exponential notation. This method optionally accepts an integer parameter specifying the number of digits after the decimal point. Also, the returned value is a string not a number. Here's an example:

let 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: Exponential notation is useful for representing numbers that are either very large or very small in magnitude. For example, 62500000000 can be written as 625e+8 or 6.25e+10.

Formatting Numbers to Fixed Decimals

You can use the toFixed() method when you want to format a number with a fixed number of digits to the right of the decimal point. The value returned by this method is a string and it has exactly specified number of digits after the decimal point. If the digits parameter is not specified or omitted, it is treated as 0. Here's an example:

let 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'

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

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

Formatting Numbers with Precision

If you want most appropriate form of a number, you can use the toPrecision() method instead. This method returns a string representing the number to the specified precision.

If precision is large enough to include all the digits of the integer part of number, then the number is formatted using fixed-point notation. Otherwise, the number is formatted using exponential notation. The precision parameter is optional. Here's an example:

let 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'

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

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

Finding the Largest and Smallest Possible Numbers

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

A number that falls outside of the range of possible numbers is represented by a constant Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY. Here's an example:

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

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

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

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

Also, check out the JavaScript math operations chapter to learn about rounding numbers, generating a random number, finding maximum or minimun value from a set of numbers, etc.

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties