What is the Number.toPrecision() method in TypeScript?
Overview
We can use the Number.toPrecision() method in TypeScript to format a number to a specified length. With this method, we can even add a decimal point or nulls to create the specified length.
Syntax
This is the syntax of the Number.toPrecision() method:
num.toPrecision(precision)
Syntax of the Number.toPrecision() method in TypeScript
Parameter values
num: This is the number we want to format to a specified length.
precision: This is the length we want to format the number to. This is an optional parameter value.
Return value
The Number.toPrecision() method returns a string. It returns the number that is formatted to the specified precision.
Example
// create some numberslet num1:number = 25.3714let num2:number = 1.112769964let num3:number = 0.5let num4:number = 5.55555// format numbers to specific lengthsconsole.log(num1.toPrecision(2))console.log(num2.toPrecision(10))console.log(num3.toPrecision(4))console.log(num4.toPrecision())
Explanation
- Lines 2–5: We create some number variables in TypeScript and assign values to them.
- Lines 8–11: We format the number according to some specified lengths and print the result to the console.