Open In App

TypeScript toFixed() Function

Last Updated : 19 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The toFixed() function in TypeScript formats a number using fixed-point notation, specifying the number of digits after the decimal point. It returns a string representation of the number, ensuring precise control over its decimal places for consistent numerical formatting.

Syntax

number.toFixed( [digits] );

Parameters:

  • number: The number you want to format.
  • digits: The number of digits to appear after the decimal point (optional).

Return Value: The toFixed() method returns a string representation of the number that does not use exponential notation and has the specified number of digits after the decimal place.

Below examples illustrates the working of toFixed() function in TypeScript :

Example 1: Formatting a Number with Default and Specified Digits

In this example, we demonstrate how to use the toFixed() function to format a number with and without specifying the number of digits after the decimal point.

let num: number = 358.423;

console.log(`num.toFixed() is ${num.toFixed()}`);
console.log(`num.toFixed(2) is ${num.toFixed(2)}`);

Output: 

num.toFixed() is 358
num.toFixed(2) is 358.42

Example 2: Formatting a Number with Various Digits

Here, we show how to format a number with different numbers of digits after the decimal point using the toFixed() function.

let num1: number = 526.123;

console.log(`num1.toFixed() is ${num1.toFixed()}`);
console.log(`num1.toFixed(4) is ${num1.toFixed(4)}`);
console.log(`num1.toFixed(7) is ${num1.toFixed(7)}`);

Output: 

num1.toFixed() is 526 
num1.toFixed(4) is 526.1230
num1.toFixed(7) is 526.1230000

FAQs-TypeScript toFixed() Function

What is the default behavior of toFixed() if no parameter is provided?

If no parameter is provided, toFixed() defaults to 0, meaning it will round the number to the nearest integer and return it as a string.

What type of value does toFixed() return?

The toFixed() function returns a string representation of the number with the specified number of decimal places.

Can toFixed() handle negative numbers for the digits parameter?

No, the digits parameter must be a non-negative integer between 0 and 100. Providing a negative number will result in a RangeError.

Does toFixed() round the number or just truncate it?

The toFixed() function rounds the number to the nearest value based on the specified number of decimal places.

What happens if the digits parameter is greater than the number of actual decimal places in the number?

If the digits parameter is greater than the number of actual decimal places, toFixed() will pad the number with zeros to the right of the decimal point.

Is the toFixed() function specific to TypeScript?

No, toFixed() is a JavaScript method that is also available in TypeScript, as TypeScript is a superset of JavaScript.


Next Article

Similar Reads

three90RightbarBannerImg