Ensure a Positive Number in JavaScript or Node.js

In a recent project, we needed to calculate differences between data points. Each data point represented an amount of money. The difference between the two data points should always be a positive number in context with prices going up or down.

This tutorial shows you how to always retrieve a positive number in JavaScript.

Node.js Series Overview

Ensure a Positive Number in JavaScript

Calculating the difference between two values may return a negative or positive number. You may always want to display a positive number aside from the context of the value going up or down. You could display arrows on a website indicating prices go up or down.

One way to always retrieve a positive number is to use the Math.abs(x) function. It returns the absolute value of x. It returns x when x is positive or zero and the negation of x if it’s negative:

Math.abs(-1)  
// 1

Math.abs(1)  
// 1

That’s it!

Explore the Library

Find interesting tutorials and solutions for your problems.