toPrecision method
The toPrecision method rounds
a number up to the given decimal
place. Unlike
Math.round,
rounding can be done not only in the
fractional part. The method parameter
specifies how many digits should remain
in the number. The rest of the digits
will be discarded. The last remaining
number will be rounded according to the
rules of mathematical rounding. If the
parameter is empty, the original number
will be returned. If the specified number
of decimal places is not achievable by
cutting off the decimal part, it converts
the number to exponential form.
Syntax
number.toPrecision(length);
Example
In this example, the number 678.19324
using toPrecision will be reduced to
4 digits, moreover, since after
1 there is the digit 9,
then according to the rules of mathematics,
one is converted to two:
let num = 678.19324;
console.log(num.toPrecision(4));
The code execution result:
678.2
Example
In this example, the number should be reduced to two digits and not only the fractional part, but also the integer will be discarded. Therefore, the number will be converted to exponential form:
let num = 678.19324;
console.log(num.toPrecision(2));
The code execution result:
6.8e+2
Example
In this example, the number 12
is reduced to 3 digits. Since
the number is an integer, then 0
will appear in the fractional part:
let num = 12;
console.log(num.toPrecision(3));
The code execution result:
12.0
Example
Let's now convert the number 12
to four digits. Two 0 will appear
in the fractional part:
let num = 12;
console.log(num.toPrecision(4));
The code execution result:
12.00
Example
Let's now convert the number
12.1 to five digits:
let num = 12.1;
console.log(num.toPrecision(5));
The code execution result:
12.100
See also
-
the
toFixedmethod
that also rounds a number to the given decimal place -
the
Math.round,Math.ceil,Math.floormethods
that round a number to an integer