You could use this...
Math.abs(x)
Math.abs() | MDN
You could use this...
Math.abs(x)
Math.abs() | MDN
What about x *= -1? I like its simplicity.
Use Math.abs() :
var x = -25;
alert(Math.abs(x)); //it will alert 25
Here are some test cases from the documentation:
Math.abs('-10'); // 10
Math.abs(-20); // 20
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
You can use Math.abs(x) for getting positive value as output. Here 'x' can be any positive or negative value
As mentioned in other comments, you won't be able to keep the precision. toFixed() is definitely not a solution and this problem has valid case scenarios.
We had to do something similar where teachers would input a grade (90.05) and were expected to keep the same number of decimals for all their students inside of a single gradebook. Teachers grade differently depending of the situation:
Teacher A | Teacher B | Teacher C
90 90.5 4.95
80 88.5 3.80
75 80.0 5.00
One way to solve this, especially if the request comes as a string (from an input, http request, etc.), is to maintain the number as a string and return a string value.
Note that this is a very crude implementation (our implementation is more fail-safe), but the idea is simple:
function absString(n) {
numberString = n.toString();
if (numberString[0] === '-') {
return numberString.substring(1);
}
else {
return numberString;
}
}
console.log(absString('-1'));
console.log(absString('-2.0'));
console.log(absString('2.0'));
console.log(absString('-0.57'));
You can use the number toFixed method as follows:
var decimalPlaces = 5 // Change this to change the number of decimals
console.log(Math.abs(-4.0).toFixed(decimalPlaces))
Math.abs(num) => Always positive
-Math.abs(num) => Always negative
You do realize, however, that for your code:
if($this.find('.pdxslide-activeSlide').index() < slideNum-1) {
slideNum = -slideNum;
}
console.log(slideNum)
If the index found is 3 and slideNum is 3,
then 3 < 3-1 => false
so slideNum remains positive??
It looks more like a logic error to me.
The reverse of abs is Math.abs(num) * -1.
You can do a simple math at this context, no need of Math.abs,
x_value = x_value * -1;
Or you can negate the value like,
x_value = -(x_value);
While negating, there is a chance to get -0, But we don't need to worry about it, since -0 == 0. Abstract equality comparison algorithm is telling so in Step 1 - c - vi.
You can multiply any number by -1 to get its opposite.
Example:
5 * -1 = -5
-5 * -1 = 5