Home >Web Front-end >JS Tutorial >How to convert negative numbers to positive numbers in javascript

How to convert negative numbers to positive numbers in javascript

青灯夜游
青灯夜游Original
2021-09-03 17:59:1215168browse

Javascript method to convert a negative number into a positive number: 1. Use the inversion operation "-" and the syntax "-x"; 2. Use the abs() function to convert the negative number by taking the absolute value of the negative number. For positive numbers, the syntax is "Math.abs(x)".

How to convert negative numbers to positive numbers in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

Javascript method of converting negative numbers to positive numbers

Method 1: Use the inversion operation

The negation operator is a unary operator, also called a unary subtraction operator.

var a = -10;
var b = -a;
console.log(b);

How to convert negative numbers to positive numbers in javascript

Method 2: Use the abs() function to get the absolute value

abs() method can return the absolute value of a number . The syntax is as follows:

Math.abs(x)

Return value: the absolute value of x. Returns NaN if x is not a number, or 0 if x is null.

Example:

var a = -100;
var b = Math.abs(a);
console.log(b);

How to convert negative numbers to positive numbers in javascript

[Recommended learning: javascript advanced tutorial

The above is the detailed content of How to convert negative numbers to positive numbers in javascript. 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