Math abs

5/5 - (1 bình chọn)

Math.abs()

The Math.abs() function returns the absolute value of a number. That is, it returns x if x is positive or zero, and the negation of x if x is negative.

Syntax

Math.abs(x)

Parameters

A number.

Return value

The absolute value of the given number.

Description

Because abs() is a static method of Math, you always use it as Math.abs(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

Behavior of Math.abs()

Passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable returns NaN. Passing null, an empty string or an empty array returns 0.

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('string'); // NaN
Math.abs();         // NaN

JavaScript: Math abs() function

This JavaScript tutorial explains how to use the math function called abs() with syntax and examples.

Description

In JavaScript, abs() is a function that is used to return the absolute value of a number. Because the abs() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the abs() function is:

Math.abs(number);

Parameters or Arguments

number The number to convert to an absolute value.

Returns

The abs() function returns the absolute value of a number.

If the abs() function is passed a non-numeric value, an array with one than one element, or an empty object as the number parameter, the abs() function will return NaN (not a number).

Note

  • The abs() function will try to convert the number parameter to a numeric value before calculating the absolute value.
  • Math is a placeholder object that contains mathematical functions and constants of which abs() is one of these functions.

Example

Let’s take a look at an example of how to use the abs() function in JavaScript.

For example:

console.log(Math.abs(-23));
console.log(Math.abs('-23'));
console.log(Math.abs(-30 * 2));

In this example, we have invoked the abs() function using the Math class.

We have written the output of the abs() function to the web browser console log, for demonstration purposes, to show what the abs() function returns.

The following will be output to the web browser console log:

23
23
60

In this example, the first output to the console log returned 23 which is the absolute value of -23. The second output to the console log also returned 23 after first converting the string value ‘-23’ to the numeric value -23 and then calculating its absolute value. The third output to the console log returned 60 which is the absolute value of the calculation of -30 x 2.

Cú pháp Math abs() trong JavaScript

Cú pháp của nó như sau:

Math.abs( x ) ;

Chi tiết về tham số

  • x − Một số.

Trả về giá trị

  • Trả về giá trị tuyệt đối của một số.

Ví dụ minh họa Math abs() trong JavaScript

<html>

   <head>
      <title>JavaScript Math abs() Method</title>
   </head>

   <body>

      <script type="text/javascript">
         var value = Math.abs(-1);
         document.write("First Test Value : " + value ); 

         var value = Math.abs(null);
         document.write("<br />Second Test Value : " + value ); 

         var value = Math.abs(20);
         document.write("<br />Third Test Value : " + value ); 

         var value = Math.abs("string");
         document.write("<br />Fourth Test Value : " + value ); 
      </script>

   </body>
</html>

Kết quả

First Test Value : 1
Second Test Value : 0
Third Test Value : 20
Fourth Test Value : NaN 

JavaScript Math abs()

The JavaScript Math.abs() function returns the absolute value of a number.

Absolute value of a number x, denoted by |x|, is defined as:

  • x if x > 0
  • 0 if x = 0
  • -x if x < 0

The syntax of the Math.abs() function is:

Math.abs(x)

abs(), being a static method, is called using the Math class name.

Math.abs() Parameters

The Math.abs() function takes in:

  • x – A Number whose absolute value is to be returned.

Return value from Math.abs()

  • Returns the absolute value of the specified number.
  • Returns NaN if:
    • Empty object
    • Non-numeric String
    • undefined/empty variable
    • Array with more than one element
  • Returns 0 if:
    • Empty String
    • Empty Array
    • null

Example 1: Using Math.abs() with Number

// Using Math.abs() with Number
value1 = Math.abs(57);
console.log(value1); // 57

value2 = Math.abs(0);
console.log(value2); // 0

value3 = Math.abs(-2);
console.log(value3); // 2

// Using Math.abs() with numeric non-Number
// single item array
value = Math.abs([-3]);
console.log(value); // 3

// numeric string
value = Math.abs("-420");
console.log(value); // 420

Output

57
0
2
3
420

Example 2: Using Math.abs() with non-Number

// Using Math.abs() with non-Number

// Math.abs() gives NaN for
// empty object
value = Math.abs({});
console.log(value); // NaN

// non-numeric string
value = Math.abs("Programiz");
console.log(value); // NaN

// undefined
value = Math.abs(undefined);
console.log(value); // NaN

// Array with >1 items
value = Math.abs([1, 2, 3]);
console.log(value); // NaN

// Math.abs() gives 0 for
// null objects
console.log(Math.abs(null)); // 0

// empty string
console.log(Math.abs("")); // 0

// empty array
console.log(Math.abs([])); // 0

Output

NaN

NaN

NaN

NaN

0

0

0

TL;DR – How to find the absolute value in JavaScript?

The math.abs() function is used to return the absolute value in JavaScript. It negates the native sign of a number and returns the relevant positive value.

JavaScript Absolute Value:

JavaScript Absolute value is a method of the Math object in JavaScript. This method helps return the absolute values of a number. Absolute value or modules essentially means a non-negative value of x.

To understand the math involved let’s first understand what absolute value actually means. Absolute value is the distance between any number and 0 on the number line. Since it is the distance, there are no negative values.

Subsequently, when a 0 is passed, JavaScript returns 0 as the distance would also be 0.

How to use the Math.abs() function?

Using the Math.abs() method is quite straightforward. The only thing that you have to keep in mind is that abs() is a static method of Math. Hence you would have to add the Math. prefix in case you want to use it.

JavaScript Absolute Value – Syntax:

Math.abs(x)

Parameters:

  • X – A number

Return Values:

  • “x” if x > 0
  • “x” if x < 0
  • “-x” if x = 0

Code and Explanation:

The best way to familiarise yourself with the JavaScript Absolute method is to practice and try breaking it. In the below code we have used math.abs() methods on a list of values.

Math.abs(-10);     // 10
Math.abs(10);       // 10
Math.abs('-10');     // 10
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs(null);     // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('Ten'); // NaN
Math.abs();         // NaN

Another important point to remember while using the math.abs() methods, is it converts strings containing a number and returns its absolute value.

Closing Thoughts – JavaScript Absolute method:

This method is mostly used before displaying a particular value. A common example would be while displaying distance on a map. In cases where you cross your destination, you are not returned with a negative value but rather the absolute value from the destination.

Sử dụng phương thức Math.abs() để lấy giá trị tuyệt đối.

Bài viết này được đăng tại [free tuts .net]

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h1>Học lập trình miễn phí tại freetuts.net</h1>
     
        <button onclick="myFunction()">Run</button>
     
        <p id="demo"></p>
     
        <script>
            function myFunction() {
                var content = '45 có giá trị tuyệt đối là ' + Math.abs(45) + '<br>';
                content = content +'-45 có giá trị tuyệt đối là ' + Math.abs(-45) + '<br>';
                content = content +'0 có giá trị tuyệt đối là ' + Math.abs(0) + '<br>';
                content = content +'-0.75 có giá trị tuyệt đối là ' + Math.abs(-0.75) + '<br>';
                content = content +'abcd có giá trị tuyệt đối là ' + Math.abs('abcd') + '<br>';
                document.getElementById("demo").innerHTML = content;
            }
        </script>
    </body>
</html>

Kết quả

1
2
3
4
5
45 có giá trị tuyệt đối là 45
-45 có giá trị tuyệt đối là 45
0 có giá trị tuyệt đối là 0
-0.75 có giá trị tuyệt đối là 0.75
abcd có giá trị tuyệt đối là NaN

Math ⭐️⭐️⭐️⭐️⭐️

Math Formulas ⭐️⭐️⭐️⭐️⭐

🌍 GIA SƯ TOÁN BẰNG TIẾNG ANH

GIA SƯ DẠY SAT

Hãy bình luận đầu tiên

Để lại một phản hồi

Thư điện tử của bạn sẽ không được hiện thị công khai.


*