TypeScript Math floor()

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

  1. Definition
  2. Syntax
  3. Examples
  4. 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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare