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 numberlet num = 0.001658853;//precision to 2 digitsconsole.log(num.toPrecision(2))//precision to 3 digitsconsole.log(num.toPrecision(3))//precision to 10 digitsconsole.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
numto2digits, by passing it as a parameter to thetoPrecision()method. - Line 8: We will format the given number
numto3digits, by passing it as a parameter to thetoPrecision()method. - Line 11: We will format the given number
numto10digits, by passing it as a parameter to thetoPrecision()method. It will add extra zeroes to format to the specified length.