TypeScript Math abs()

In this chapter, we will explore the Math.abs() method in TypeScript. This method returns the absolute value of a number. Understanding how to use Math.abs() is useful for ensuring that values are non-negative, which can be important in various mathematical calculations and algorithms.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The Math.abs() method returns the absolute value of a number, which is the number without its sign. If the number is positive or zero, it returns the number unchanged. If the number is negative, it returns the number multiplied by -1.

2. Syntax

Math.abs(x);

Parameters

  • x: A number whose absolute value is to be returned.

Return Value

The method returns the absolute value of the given number.

3. Examples

Let's look at some examples to understand how Math.abs() works in TypeScript.

Example 1: Basic Usage

In this example, we use Math.abs() to find the absolute value of a positive number.

let num: number = 42;
let result = Math.abs(num);
console.log(result); // Output: 42

Example 2: Finding the Absolute Value of a Negative Number

In this example, we use Math.abs() to find the absolute value of a negative number.

let num: number = -42;
let result = Math.abs(num);
console.log(result); // Output: 42

Example 3: Absolute Value of Zero

In this example, we use Math.abs() to find the absolute value of zero.

let num: number = 0;
let result = Math.abs(num);
console.log(result); // Output: 0

Example 4: Absolute Value of a Decimal Number

In this example, we use Math.abs() to find the absolute value of a decimal number.

let num: number = -123.456;
let result = Math.abs(num);
console.log(result); // Output: 123.456

Example 5: Using Math.abs() with Variables

In this example, we use Math.abs() with variables to find their absolute values.

let a: number = -5;
let b: number = 15;
let resultA = Math.abs(a);
let resultB = Math.abs(b);
console.log(resultA); // Output: 5
console.log(resultB); // Output: 15

Example 6: Using Math.abs() with Expressions

In this example, we use Math.abs() with expressions to find the absolute value of the result.

let num1: number = -5;
let num2: number = 3;
let result = Math.abs(num1 * num2 - num2);
console.log(result); // Output: 12

4. Conclusion

In this chapter, we explored the Math.abs() method in TypeScript, which is used to return the absolute value of a number. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use Math.abs() effectively can help in various mathematical calculations and algorithms, especially when ensuring values are non-negative is important.

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