In this chapter, we will explore the toFixed()
method for numbers in TypeScript. This method formats a number using fixed-point notation. Understanding how to use toFixed()
is useful for formatting numbers to a specified number of decimal places.
Table of Contents
- Definition
- Syntax
- Examples
- Conclusion
1. Definition
The toFixed()
method formats a number using fixed-point notation. This method returns a string representation of the number with a specified number of digits after the decimal point.
2. Syntax
number.toFixed(digits?);
Parameters
digits
(optional): An integer specifying the number of digits to appear after the decimal point. It must be in the range of 0 to 20, inclusive. If omitted, the default is 0.
Return Value
The method returns a string representing the number in fixed-point notation.
3. Examples
Let's look at some examples to understand how toFixed()
works in TypeScript.
Example 1: Basic Usage
In this example, we use toFixed()
to format a number with no decimal places.
let num: number = 123.456;
let result = num.toFixed();
console.log(result); // Output: "123"
Example 2: Specifying Decimal Places
In this example, we use toFixed()
to format a number with two decimal places.
let num: number = 123.456;
let result = num.toFixed(2);
console.log(result); // Output: "123.46"
Example 3: Formatting with More Decimal Places
In this example, we use toFixed()
to format a number with five decimal places.
let num: number = 123.456;
let result = num.toFixed(5);
console.log(result); // Output: "123.45600"
Example 4: Using toFixed()
with Small Numbers
In this example, we use toFixed()
to format a small number with three decimal places.
let num: number = 0.000123;
let result = num.toFixed(3);
console.log(result); // Output: "0.000"
Example 5: Using toFixed()
with Large Numbers
In this example, we use toFixed()
to format a large number with two decimal places.
let num: number = 987654321.123;
let result = num.toFixed(2);
console.log(result); // Output: "987654321.12"
Example 6: Rounding Behavior
In this example, we use toFixed()
to demonstrate how it handles rounding.
let num: number = 1.005;
let result = num.toFixed(2);
console.log(result); // Output: "1.01"
4. Conclusion
In this chapter, we explored the toFixed()
method for numbers in TypeScript, which is used to format a number using fixed-point notation. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use toFixed()
effectively can help in various tasks where precise formatting of numerical output is required, especially when dealing with currency, measurements, and other decimal-based data.
Comments
Post a Comment
Leave Comment