In this chapter, we will explore the Math.floor()
method in TypeScript. This method returns the largest integer less than or equal to a given number. Understanding how to use Math.floor()
is useful for rounding numbers down to the nearest integer.
Table of Contents
- Definition
- Syntax
- Examples
- Conclusion
1. Definition
The Math.floor()
method returns the largest integer less than or equal to a given number. This method always rounds a number down to the nearest integer.
2. Syntax
Math.floor(x);
Parameters
x
: A number to be rounded down.
Return Value
The method returns the largest integer less than or equal to the given number.
3. Examples
Let's look at some examples to understand how Math.floor()
works in TypeScript.
Example 1: Basic Usage
In this example, we use Math.floor()
to round a positive decimal number down to the nearest integer.
let num: number = 4.7;
let result = Math.floor(num);
console.log(result); // Output: 4
Example 2: Rounding a Negative Decimal Number
In this example, we use Math.floor()
to round a negative decimal number down to the nearest integer.
let num: number = -4.7;
let result = Math.floor(num);
console.log(result); // Output: -5
Example 3: Rounding Whole Numbers
In this example, we use Math.floor()
to round whole numbers. Whole numbers remain unchanged.
let num1: number = 5;
let num2: number = -5;
console.log(Math.floor(num1)); // Output: 5
console.log(Math.floor(num2)); // Output: -5
Example 4: Rounding a Positive Decimal Number Less Than .5
In this example, we use Math.floor()
to round a positive decimal number less than .5 down to the nearest integer.
let num: number = 4.3;
let result = Math.floor(num);
console.log(result); // Output: 4
Example 5: Using Math.floor()
with Expressions
In this example, we use Math.floor()
with expressions to round the result down to the nearest integer.
let num1: number = 3.7;
let num2: number = 2.2;
let result = Math.floor(num1 + num2);
console.log(result); // Output: 5
Example 6: Rounding Small Positive Decimal Numbers
In this example, we use Math.floor()
to round small positive decimal numbers down to the nearest integer.
let num: number = 0.999;
let result = Math.floor(num);
console.log(result); // Output: 0
4. Conclusion
In this chapter, we explored the Math.floor()
method in TypeScript, which is used to return the largest integer less than or equal to a given number. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use Math.floor()
effectively can help in various mathematical calculations and scenarios where rounding numbers down is required.
Comments
Post a Comment
Leave Comment