FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

JavaScript Numbers: A Modern Reference

on in JavaScript
Last modified on

Table of Contents

JavaScript is a dynamically typed language, and it doesn’t have specific integer or floating-point types, unlike some other languages. In JavaScript, all numbers are represented as 64-bit (8 bytes) floating-point numbers, which provides a range from approximately 5e-324 (negative) to 1.7976931348623157e+308 (positive).

This reference will cover JavaScript numeric literals, objects, and the default JavaScript operators used to manipulate numbers.

Precision

In JavaScript, all numbers are 64-bit (8 bytes) floating-point numbers. Integers, represented without a decimal point or exponent notation, are considered reliable up to 15 digits (9e15). Floating-point numbers have their limitations and might not provide absolute precision. For example, performing 0.06 + 0.01 results in 0.06999999999999999 instead of 0.07.

To Infinity and Beyond

JavaScript handles numbers within a generous range. If you attempt to work with numbers outside this range, JavaScript will return a special constant, either -Infinity or Infinity, representing negative or positive overflow, respectively. You can also test for infinity using the Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY property.

javascriptCopy code

let result = 2;
for (let i = 1; result !== Infinity; i++) {
   result = result * result;
   console.log(`${i}:${result}`);
}

/* Outputs:
1:4
2:16
3:256
4:65536
5:4294967296
6:18446744073709552000
7:3.402823669209385e+38
8:1.157920892373162e+77
9:1.3407807929942597e+154
10:Infinity
*/

Division by zero also generates an infinity result.

console.log(255 / 0);  // Outputs: Infinity
console.log(-255 / 0); // Outputs: -Infinity

Octal and Hexadecimal Numbers

JavaScript can handle octal and hexadecimal numbers, though it’s not universally supported in all browsers. Numeric constants are considered octal if they are preceded by a zero and hexadecimal if they are preceded by 0x. It’s essential to avoid preceding numbers with zero unless you specifically intend to convert them.

const octal = 0o377;
const hex = 0xFF;
console.log(`Octal: ${octal}`);         // Outputs: 255
console.log(`Hex: ${hex}`);             // Outputs: 255
console.log(`Octal=255: ${octal === 255}`); // Outputs: true
console.log(`Hex=255: ${hex === 255}`);   // Outputs: true
console.log(`Hex=0377: ${hex === 0x377}`); // Outputs: true
console.log(`Octal=0xFF: ${octal === 0xff}`); // Outputs: true

To convert a number to a base other than 10, you can use the toString() method with the desired base as the first argument (16 for hexadecimal, 8 for octal, 2 for binary).

const num = 255;
console.log(`${num.toString(16)} hex`);   // Outputs: ff
console.log(`${num.toString(8)} octal`);  // Outputs: 377
console.log(`${num.toString(2)} binary`); // Outputs: 11111111

Arithmetic Operators

JavaScript provides various arithmetic operators:

// Addition (Concatenation)
let x = 5;
x += 5; // Same as x = x + 5;

// Subtraction (Unary conversion)
let y = -10;

// Multiplication
let product = x * y;

// Division
let quotient = x / y;

// Remainder/Modulus
let remainder = x % y;

// Increment (pre/post)
x++;  // x = 6;
x--;  // x = 5;

// The increment/decrement operator can be either before or after the variable.
let z = 5;
console.log(z++); // Outputs: 5
console.log(z);   // Outputs: 6

let w = 5;
console.log(++w); // Outputs: 6
console.log(w);   // Outputs: 6

Bitwise Operators

Bitwise operations in JavaScript work with 32-bit signed integers. JavaScript performs behind-the-scenes magic to make it appear as if bitwise operations are applied to 32-bit integers, even though all numbers are stored as 64-bit floating point.

Here are some common bitwise operators:

let a = 5; // Binary: 00000101
let b = 3; // Binary: 00000011

let resultAnd = a & b; // Bitwise AND (result: 00000001 - Decimal 1)
let resultOr = a | b;  // Bitwise OR (result: 00000111 - Decimal 7)
let resultXor = a ^ b; // Bitwise XOR (result: 00000110 - Decimal 6)
let resultNot = ~a;    // Bitwise NOT (result: 11111010 - Decimal -6)
let resultLeftShift = a << 2;  // Bitwise Left Shift (result: 00010100 - Decimal 20)
let resultRightShift = a >> 1; // Bitwise Right Shift (result: 00000010 - Decimal 2)
let resultUnsignedRightShift = a >>> 1; // Unsigned Right Shift (result: 00000010 - Decimal 2)

Be cautious when using bitwise operators, especially when you intended to use logical operators. Always use parentheses to ensure proper evaluation.

parseInt(string[, radix])

The parseInt function converts a string to an integer with the specified radix (base). If no radix is specified, it assumes base 10. Avoid leading zeros in your string to prevent octal interpretation.

console.log(parseInt('ff', 16));      // Outputs: 255
console.log(parseInt('09'));         // Outputs: 9 (octal conversion)
console.log(parseInt('09', 10));      // Outputs: 9 (base 10 forced)
console.log(parseInt('123.85'));     // Outputs: 123
console.log(parseInt('0123.85'));    // Outputs: 83 (octal conversion!)
console.log(parseInt('0123.85', 10));// Outputs: 123 (base 10 forced)
console.log(parseInt('$123.85', 10));// Outputs: NaN (Not a Number)
console.log(parseInt('1,423.8', 10));// Outputs: 1
console.log(parseInt('0x7', 10));    // Outputs: NaN (hex, not base 10)
console.log(parseInt('255', 2));     // Outputs: NaN (binary, only 1 and 0)
console.log(parseInt('10', 2));      // Outputs: 2

parseFloat(string)

The parseFloat function parses a string argument and returns a floating-point number. It can handle decimal points and exponential notation.

console.log(parseFloat('3.14'));       // Outputs: 3.14
console.log(parseFloat('314e-2'));     // Outputs: 3.14
console.log(parseFloat('0.0314E+2'));  // Outputs: 3.14
console.log(parseFloat('3.14more'));   // Outputs: 3.14
console.log(parseFloat('More 3.14'));  // Outputs: NaN

isNaN(value)

The isNaN function checks if a value is “Not-a-Number.” Keep in mind that isNaN returns true for anything that is not a number, which can lead to unexpected results.

console.log(isNaN('Hello'));  // Outputs: true
console.log(isNaN('123'));    // Outputs: false
console.log(isNaN(123));      // Outputs: false
console.log(isNaN(NaN));      // Outputs: true

To check if a value is a valid number, use isNaN in conjunction with parseFloat or parseInt.

Number.isNaN(value)

To avoid the inconsistencies of the global isNaN function, use Number.isNaN. It returns true only if the value is NaN.

console.log(Number.isNaN('Hello')); // Outputs: false
console.log(Number.isNaN('123'));   // Outputs: false
console.log(Number.isNaN(123));     // Outputs: false
console.log(Number.isNaN(NaN));     // Outputs: true

Number Properties

JavaScript provides some useful number-related properties:

console.log(Number.MAX_VALUE); // Outputs: 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // Outputs: 5e-324
console.log(Number.POSITIVE_INFINITY); // Outputs: Infinity
console.log(Number.NEGATIVE_INFINITY); // Outputs: -Infinity
console.log(Number.NaN); // Outputs: NaN

Number Methods

There are various methods you can use with JavaScript numbers:

toFixed()

The toFixed method allows you to format a number with a specific number of decimal places.

const num = 123.45678;
console.log(num.toFixed(2)); // Outputs: "123.46"

toPrecision()

The toPrecision method formats a number using a specified length.

const num = 123.45678;
console.log(num.toPrecision(3)); // Outputs: "123"

toExponential()

The toExponential method returns a string representing a number in exponential notation.

const num = 12345;
console.log(num.toExponential(2)); // Outputs: "1.23e+4"

This reference covers the basics of JavaScript numbers, their representation, operators, and methods available in modern ES6 JavaScript. To learn more, explore the vast world of JavaScript programming with numbers.

NEW! Learn JavaScript by example. Code snippets, how-to’s and tutorials. Try now!

Related posts