Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is the toPrecision() method in JavaScript?

Umme Ammara

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The toPrecision() method rounds a number to a specified precision or significant digits. If the rounded number requires more digits than the original number, the method adds decimals and nulls to create the specified format.

If the toPrecision() method is called on an object other than a number, a TypeError occurs.

Syntax

The toPrecision() method is declared as follows:

Parameters

The toPrecision() method takes an optional single parameter x, which is an integer number representing the number of significant digits.

  • If the value of x is not within the range 0 - 100, a RangeError occurs.

  • If x is not an integer, it is rounded to the nearest integer.

Return value

The toPrecision() method returns a string rounded to x significant digits. If x is not specified, the number is returned in string form without any rounding.

Examples

The following code shows the use of the toPrecision() method in JavaScript:

//Example 1
var num = 1.234567;
console.log(num.toPrecision());
//Example 2
console.log(num.toPrecision(4));
//Example 3
console.log(num.toPrecision(2));
//Example 4
console.log(num.toPrecision(1));

RELATED TAGS

javascript

CONTRIBUTOR

Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring