All programming languages appreciate the significance of numbers in computing and likewise provide utilities to easily work with them. JavaScript is no way behind — the language comes packed with a ton of things to facilitate in working with numbers.

In this chapter, we'll explore some methods natively available to JavaScript numbers via the Number class. Specifically we'll go over the different ways to round numbers and then consider conversions to different numerical bases including binary, octal and hexadecimal.

Rounding to significant figures

The toPrecision() method rounds a number to a given number of significant digits.

Its syntax is pretty basic:


It takes in a precision argument and returns back a string holding number in its rounded form.

Note that precision must be between 1 and 100. Giving a value out of this range would result in an error. Moreover, if precision is a non-integer value, it is rounded to the nearest integer.

Shown below are a bunch of examples.

First, let's see how are integers rounded:

58 .toPrecision(2)
58 .toPrecision(3)
124 .toPrecision(3)
124 .toPrecision(4)

In the first statement, calling toPrecision() on 58 has no effect since the number already has 2 significant figures. In the second statement, the function returns a string with 0 added after the decimal point to act as the third significant digit. A similar explanation applies to 124.

Why is there a space in 58 .toPrecision(2)?

Notice the space between each number and . character given above. It is necessary. Why?

This ensures that the JavaScript interpreter doesn't parse the . as a decimal point.

Removing the space, as in 58.toPrecision() would lead to an error. This is because with the space removed, the interpreter would think that . is a decimal point and so would be followed by numeric digits, but this doesn't happen — instead the word toPrecision() follows and this counts as invalid code, causing the error.

Now let's work with a couple of floats:

1.2386 .toPrecision(2)
1.2386 .toPrecision(3)
1.2386 .toPrecision(4)

In the first statement, the number 1.2386 is rounded to 2 significant figures i.e to the first decimal place. This causes the number to be rounded down to 1.2. In the second statement, the same number is rounded to 3 s.f, i.e to the second decimal place. This rounds the number up to 1.24.

A similar explanation applies to the last statement as well.

Moving on, in cases where precision is less than the number of digits already in the given number, the returned string is in exponential notation.

Consider the snippet below:

58 .toPrecision(1)
124 .toPrecision(1)
124 .toPrecision(2)
178 .toPrecision(2)
17000 .toPrecision(1)
17000 .toPrecision(2)
17000 .toPrecision(3)
17000 .toPrecision(4)
17000 .toPrecision(5)

In the first statement, the number 58 has two digits while the arg to toPrecision() is 1. This leads to the return value being in exponential notation. 58 rounded to 1 s.f. is 60, which is equivalent to 6e+1.

A similar explanation applies to the rest of the given statements.

In the last statement, the number of digits in 17000 and the arg to the toPrecision() method are both equal to one another, i.e. 5, so there is no conversion to exponential notation in the returned stringified number.

In cases where the resulting number (after this rounding) could, otherwise, be easily represented in normal decimal notation, this conversion to exponential notation could pose a slight problem.

Is there any way to solve it?

Hmm. Well, there is no way to do so natively in JavaScript. But we could create our own function to solve this problem.

In the upcoming exercise, we'll get you to create such a function utilising the return value of the toPrecision() number method.

Anyways, moving on, sometimes instead of wanting to round a number to given significant figures, it's desired to round it to given decimal places. This can be accomplished using the toFixed() method.

Rounding to decimal places

The toFixed() method rounds a number to a given decimal places and returns back the result in the format of a string (akin to toPrecision()).

Let's see its syntax:


digits is the number of digits to place after the decimal point in the returned stringified number. By default, digits is set to 0.

Here's a demonstration of toFixed():

1 .toFixed()
1 .toFixed(0)
1 .toFixed(1)
1 .toFixed(2)
1 .toFixed(5)

The toFixed() method is commonly used in applications where we deal with billing, currency and financial statistics. Currency is typically represented with 2 decimal places i.e $0.00, $2.25, $100.07, etc, which means that the invocation toFixed(2) is made on such numbers.

In the code below, we log a simple message containing some billing info:

var price = 3; // price in $
var qty = 10;

console.log('Your total bill is: $' + (price * qty).toFixed(2));
Your total bill is: $30.00

Are you thinking as to why is this method called 'toFixed'?

Well there is a simple logic to it.

Why is it called to 'toFixed'?

Naming of an identifier shall be the first step in understanding what it's meant for. Let's where does the name 'toFixed' come from.

In programming, we have floating-point numbers where the decimal point literally floats — it's not fixed at a given position. Unlike this, in fixed-point numbers, the decimal point is fixed — there is always a fixed number of digits after it.

Coming back to toFixed(), this method converts a given number into fixed-point representation, likewise we call it 'toFixed'.


Converting to exponential notation

To convert any number into exponential notation, also known as scientific notation, we use the toExponential() method.

The toExponential() method takes in an argument and returns back a string holding its equivalent value in exponential notation.

Here's the syntax:


fractionDigits gives the number of digits to put after the decimal point in the final exponential notation. If omitted, the number is converted to the most appropriate exponential-notation equivalent.

Let's see some quick examples:

152 .toExponential(0)
152 .toExponential(1)
152 .toExponential(2)
152 .toExponential()

Shown below are even more examples, this time using actual floating-point numbers:


Converting numbers to different bases

One fairly useful method of numbers in JavaScript is the toString() method.

Although it merely converts a number into a string when called with no arguments, if it's provided with an argument, it will perform conversion of the number into the given base n representation.

The argument has to be a number and is generally called the radix of the converted number. Radix is simply the base, we wish to convert a number into.

Some common bases are base 2, known as binary; base 8, known as octal; and base 16, known as hexadecimal. The number system we use is built on the base 10, and commonly referred to as the decimal number system.

To illustrate this discussion, following we convert the decimal number 15 into all the three representations - binary, octal and hexadecimal:

var num = 15;

// conversion to binary
var binNum = num.toString(2); // "1111"

// conversion to octal
var octNum = num.toString(8); // "17"

// conversion to hexadecimal
var hexNum = num.toString(16); // "f"
In hexadecimal, f stands for the number 15.
Since we can't have the bases 0 or 1 to represent numbers, calling toString(0) or toString(1) will throw errors.

These three conversions are by far the most common out there, but you can still experiment with other bases. See what each one returns!

And once again, note that this method also converts the number into a string; which is, in effect, its sole purpose. Therefore, before working with the converted number just make sure to parse it using parseInt() and the respective base of the number.

Convert the binary number 10110 into hexadecimal representation, and save the result in a variable hexNum.

The following code has been set up for you to start with:

var binNum = "10110";
var hexNum = // put the result here
Note that the final result should be a string.

First we'll need to parse binNum into a number and then convert this to a hexadecimal number.

To parse binNum we'll use parseInt(binNum, 2) and then to convert its output into hexadecimal, we'll use toString(16).

Combining both these functions, we have the following code:

var binNum = "10110";
var hexNum = parseInt(binNum, 2).toString(16); // "16"