JavaScript(JS) number method - toprecision

https‮w//:‬ww.theitroad.com

The toPrecision() method is a built-in method of the Number object in JavaScript. It returns a string representation of the number with a specified precision.

Here's an example usage:

const num = 1234.56789;

console.log(num.toPrecision(4)); // "1235"

In the above example, the toPrecision() method is called on the num variable, which is assigned the value 1234.56789. The method is passed the argument 4, which specifies that the output should have four significant digits. The method returns a string representation of the number with a precision of four significant digits, which is "1235".

If the argument passed to toPrecision() is greater than the number of digits in the original number, the method returns a string with trailing zeros to fill the specified precision. For example:

const num = 123.4;

console.log(num.toPrecision(5)); // "123.40"

In this example, the toPrecision() method is called on the num variable, which is assigned the value 123.4. The method is passed the argument 5, which specifies that the output should have five significant digits. Since the original number only has three significant digits, the method returns a string with trailing zeros to fill the specified precision, which is "123.40".