JavaScript Number toPrecision() method - JavaScript Tutorial

JavaScript Number toPrecision() method

BLUF: This tutorial on JavaScript Number toPrecision() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Number toPrecision() method

Understanding JavaScript Number toPrecision() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience