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 numbers
let num1:number = 25.3714
let num2:number = 1.112769964
let num3:number = 0.5
let num4:number = 5.55555
// format numbers to specific lengths
console.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.

Free Resources