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
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.
precision must be between
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:
In the first statement, calling
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
Why is there a space in
Notice the space between each number and
. character given above. It is necessary. Why?
. 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:
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
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:
In the first statement, the number
58 has two digits while the arg to
1. This leads to the return value being in exponential notation.
58 rounded to 1 s.f. is
60, which is equivalent to
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?
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
Rounding to decimal places
toFixed() method rounds a number to a given decimal places and returns back the result in the format of a string (akin to
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
Here's a demonstration of
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));
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 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:
Shown below are even more examples, this time using actual floating-point numbers:
Converting numbers to different bases
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.
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"
fstands for the number 15.
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
The following code has been set up for you to start with:
var binNum = "10110"; var hexNum = // put the result here
First we'll need to parse
binNum into a number and then convert this to a hexadecimal number.
binNum we'll use
parseInt(binNum, 2) and then to convert its output into hexadecimal, we'll use
Combining both these functions, we have the following code:
var binNum = "10110"; var hexNum = parseInt(binNum, 2).toString(16); // "16"