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

青灯夜游
Release: 2023-01-07 11:47:15
Original
15139 people have browsed it

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);
Copy after login

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)
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template