Home > Article > Web Front-end > How to get the absolute value of a javascript number
How to obtain the absolute value of a javascript number: 1. Use the abs() method of the Math object, with the syntax "Math.abs(number)"; 2. Use the "-" operator, with the syntax "-number"; 3. Use the "*" operator and the sqrt() method, with the syntax "Math.sqrt(a*a)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript takes the absolute value of a number
Method 1: Use Math.abs()
var aaa=-20; console.log(Math.abs(aaa));
Method 2: Use the "-" operator
var aaa=-20; console.log(-aaa);
Note: Use the "-" operator to get When using absolute values, you must ensure that the number is negative.
Method 3: Use the "*" operator and the sqrt() method
First use the "*" operator to find the square value, and then use the sqrt() method to get Square root
var a=-25; a=a*a; a=Math.sqrt(a); console.log(a);
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to get the absolute value of a javascript number. For more information, please follow other related articles on the PHP Chinese website!