Home  >  Article  >  Web Front-end  >  How to get the absolute value of a javascript number

How to get the absolute value of a javascript number

青灯夜游
青灯夜游Original
2022-01-18 17:25:3029968browse

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)".

How to get the absolute value of a javascript number

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));

How to get the absolute value of a javascript number

Method 2: Use the "-" operator

var aaa=-20;
console.log(-aaa);

How to get the absolute value of a javascript number

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);

How to get the absolute value of a javascript number

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn