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.
This is the syntax of the Number.toPrecision()
method:
num.toPrecision(precision)
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.
The Number.toPrecision()
method returns a string. It returns the number that is formatted to the specified precision.
// 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())