JavaScript Number toPrecision() method

The toPrecision method in JavaScript provides a string representation of a number with a defined level of precision.

Syntax

The syntax for the toPrecision method is illustrated as follows:

Example

Number.toPrecision(digits)

Parameter

digits - This parameter is not mandatory. It specifies the number of decimal places to which the number should be accurate.

Return

A string that signifies a numerical value with a precise count of digits following the decimal separator.

JavaScript Number toPrecision method example

In this section, we will explore the toPrecision method by examining multiple examples.

Example 1

Let’s examine a straightforward illustration of the toPrecision function.

Example

<script>

var a=98.9721;

document.writeln(a.toPrecision());

</script>

Output:

Example 2

Let’s examine an example that demonstrates how to round a number to a specified number of decimal places.

Example

<script>

var a=98.9721;

document.writeln(a.toPrecision(2));

</script>

Output:

Input Required

This code uses input(). Please provide values below: