In JavaScript, we have a method called absolute - abs()
to convert a negative number into positive number.
Usage - Math.abs(-7);
Now, we will see how we can perform the same operation without using the built-in absolute method,
const negativeToPositive = num =>{
if(num < 0){
return num * -1;
}
return num;
}
console.log(negativeToPositive(-8));
Here we have written a function which based on the input number given, converts the negative number input to positive and for positive number input, it just returns the number.
Hope this was helpful😊.
Top comments (3)
Why?
Under what circumstances would you NOT want to use abs()? If I saw that function name I would be assuming there was an edge case that abs on its own didn't handle
Hi,
Sorry, I missed to add that this was asked in a interview. abs() works fine.
So another answer would be to convert it to a string, replace "-" with "" and convert back to a number.