JavaScript Numbers

Introduction

What comes to your mind when you hear the word, Numbers?

Something like this, right?

Numbers are of different types: decimal numbers, positive and negative integers, fractions, and whole numbers……

Suppose you are familiar with any programming language. In that case, you may already know that different data types, like short, int, float, long, double, can accommodate different types of numbers in programming languages. However, JavaScript sets itself apart in this respect; there is only one type of Number in JavaScript. JavaScript is an untyped language. This means that a JavaScript variable can hold a value of any data type.

Sounds interesting, right?

JavaScript numbers are always stored as double-precision floating-point numbers, following the international IEEE 754 standard. This blog will teach you everything you need to know about JavaScript Numbers.

Numbers

In modern JavaScript, there are two types of numbers

  • Regular Numbers: They are stored in 64-bit format and are also known as double-precision floating-point numbers; these are the numbers that we use most of the time in JavaScript and will be discussed in this blog.
  • BigInt Numbers: They are used to represent integers of arbitrary length; they are needed because a regular number cannot exceed 2^53 or less than -2^53. They will be discussed in the upcoming blogs.

How to Write Numbers

Numbers are primitive data types in JavaScript. Consider the following example

const a = 10;   // A number without decimal
const b = 10.789;  // A number with decimal

Writing Extra Large and Extra Small numbers

Imagine we need to write 1 billion. The obvious way to do so is:

let billion = 1000000000;

An underscore _ can also be used as the separator; the _ plays the role of syntactic sugar as it makes the number more readable. The JS engine will ignore the _ between digits. So 1 billion can we written as

let billion = 1_000_000_000;

Extra large or extra small numbers can be written with exponent/scientific notation

const x = 134e6;  //134000000
const y = 134e-5; //0.00134

Note that e multiplies the number by 1 with the given zeros count. 

// e6 implies 1000000
134e6 = 134 * 1000000 
// e5 implies 100000
1.23e5 = 1.23 * 100000

A negative number after e signifies division by 1 with the given number of zeroes.

134e-3 = 134/1000 = 0.134
1.23e-6 = 1.23/1000000 = 0.00000123

Writing Hexadecimal, Binary and Octal Numbers

Hexadecimal numbers are widely used in JavaScript. They are written using a shorthand notation using 0x and then the number.

let a = 0xff;
console.log(a)

This will print 255, the decimal number corresponding to the hex code 0xff.

Binary numbers are also supported by JavaScript using the 0b prefix.

let a = 0b111110011; // Binary form of 4999
console.log(a)

Likewise octal numbers are supported by the 0o prefix.

let a = 0o345; // Octal form of 229
console.log(a)

The Number() constructor

According to MDN docs, The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function. The Number() constructor creates a Number object; it takes in the numeric value of the object being created as a parameter. Let's look at some examples. 

When used as a function, Number(value) converts a string or other value to the Number type; if the value cannot be converted, it returns NaN, which is illustrated in the following examples.

Number('343')  // returns the number 343
Number('123') === 123  // true
Number("coding ninja")  // NaN
Number(undefined)  // NaN

Now let's have a look at some of the important and commonly used methods of Numbers in JavaScript.

Methods of Number()

  1. toString(base): This method returns a string representation of the number in the numeral system with the given base. Note that the base can vary from 2 to 36; the default base is 10.

let a = 124;
// Base 16 correspond to hex colors
console.log(a.toString(16));
// Base 2 corresponds to binary numbers
console.log(a.toString(2));
// Base 10 corresponds to decimal
// numbers
console.log(a.toString(10));
The output is:

We can also call the method directly on a number without needing to declare it using two dots .. as illustrated below

console.log(123456..toString(2));
The output is
11110001001000000
  1. isSafeInteger(): The Number.isSafeInteger() method determines whether the provided value is a number that is a safe integer, safe integer implies an integer that can be exactly represented as IEEE-754 double-precision number and whose IEEE 754 representation cannot be the result of rounding any other integer to fit the IEEE 754 representation. The method is illustrated below:
console.log(Number.isSafeInteger(34));
console.log(Number.isSafeInteger(Math.pow(2, 53)));
The output is:

true

false

2. Rounding Operations: There are several ways to round a number; the floor method rounds down a number, the ceil method rounds up a number, and the round method rounds to the nearest integer. All the three methods are used in the below program

console.log(Math.floor(5.7));
console.log(Math.ceil(5.7));
console.log(Math.round(5.7));

The output is:

5

6

6

3. Testing Methods: The methods isFinite() and isNan() are used to check whether the passed value is a regular number, not NaN/Infinity/-Infinity and NaN respectively.

console.log(isNaN(NaN));
console.log(isFinite("142"));

The output is:

true

true

Several methods and properties of the Number() constructor are left for you to explore while coding; you may refer to this to know more.

Using the Number object to assign values to numeric variables

Assigning the maximum value, minimum value, positive and negative infinity is quite easy in JavaScript. The values can be assigned using the properties of the Number object, as illustrated below

const biggestNum     = Number.MAX_VALUE
const smallestNum    = Number.MIN_VALUE
const infiniteNum    = Number.POSITIVE_INFINITY
const negInfiniteNum = Number.NEGATIVE_INFINITY
const notANum        = Number.NaN
console.log(biggestNum);
console.log(smallestNum);
console.log(infiniteNum);
console.log(negInfiniteNum);
console.log(notANum);

The output is:

1.7976931348623157e+308

5e-324

Infinity

-Infinity

NaN

We have discussed a few of the important methods and properties of the Number() constructor; you will come to know more about them and their usage once you start to code. For now let's take a look at some of the frequently asked questions. 

Frequently Asked Questions

Q1) What are JavaScript Numbers?
Ans 1) The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding.

Q2) How does JavaScript store numbers?
Ans 2) JavaScript numbers are all floating-point, stored according to the IEEE 754 standard.

Q3) How do you check if it is a number in JavaScript?
Ans 3) You can use the JavaScript typeOf method, if the variable passed is a number, it will return a string named number. This is illustrated in the following example

console.log(typeof 42);

The output will be number.

Key Takeaways

This blog discussed JavaScript Numbers in depth. Several methods were discussed along with examples, but there are many more concepts you need to be well acquainted with within JavaScript. Our Guided Path on JavaScript will help you out. If you are preparing for JavaScript Interviews, check out the blog Javascript Interview Questions

We hope you found this blog useful. Feel free to let us know your thoughts in the comments section.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think