JavaScript Negative Number

Shraddha Paghdar Dec 10, 2021
JavaScript Negative Number

The number is one of the most popular and widely used data types in JavaScript. The JavaScript Number data type is a 64-bit binary format IEEE 754 double-precision value, like double in Java or C#.

JavaScript numbers can also be expressed in literal forms like 0o13, 0b101, 0x0A. JavaScript offers different methods for working with numbers like Number.isInteger(), Number.parseInt(), Number.prototype.toFixed(), etc. JavaScript provides the Math object with its own properties and methods for working with numbers.

In today’s article, we will introduce how to get a negative number in JavaScript.

Negative Number in JavaScript Using Math.abs()

This is a built-in function of JavaScript.This function returns the absolute value of a number. It takes the input parameter and returns the positive value of the number independently of the input. It means if the input parameter is negative, it will return the positive value.

Syntax:

Math.abs(x)

This is the static method of Math. It does not require the creation of the Math object to call this function. If an array with more than 1 parameter, an empty object, a non-numeric string, or an empty variable is passed, NaN is returned. For more information about the ES6 function, read the documentation of Math.abs() method.

console.log(Math.abs(8) * -1);
console.log(Math.abs(-8) * -1);
console.log(8 * -1);
console.log(-8 * -1);

In the above example, we have passed the value 8 inside Math.abs() and multiplied it with -1. Users can directly pass the number and multiply it with -1. The only difference between Math.abs() and directly multiplying with -1 is that prior will always return a negative number irrespective of the input parameter but later may return a positive value if the input parameter is a negative number.

Output:

-8
-8
-8
8
Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - JavaScript Number