What is the toPrecision() method in TypeScript?

Overview

We use the toPrecision() method to format a number to a specified length in TypeScript.

The method adds a decimal point or zeroes if needed while formatting the number to a specified length.

We will use the below syntax for this.

Syntax

number.toPrecision(x)

Parameters

This method takes a number of digits as a parameter to format a number to a specified length.

Return value

This method will return a number after formatting the given number to a specified length.

Let's look at the below example.

Code

//given number
let num = 0.001658853;
//precision to 2 digits
console.log(num.toPrecision(2))
//precision to 3 digits
console.log(num.toPrecision(3))
//precision to 10 digits
console.log(num.toPrecision(10))

Explanation

In the code snippet above:

  • Line 2: We declare and initialize the number using num.
  • Line 5: We will format the given number num to 2 digits, by passing it as a parameter to the toPrecision() method.
  • Line 8: We will format the given number num to 3 digits, by passing it as a parameter to the toPrecision() method.
  • Line 11: We will format the given number num to 10 digits, by passing it as a parameter to the toPrecision() method. It will add extra zeroes to format to the specified length.

        Free Resources