For example we can use simple mathematics logic or we can use build-in function. But we also want to know which method is faster in converting negative number to positive.
2 ways to convert negative number to positive.
- Using simple mathematics logic
- Using pre-build function Math.Abs()
Method 1: Using mathematics logic.
Here first we have to make sure that the value should be negative, for that we can check with if condition that number value should be less then 0 (ZERO). So we can multiply it with -1, as by multiplying it gives us a positive value.
// function which convert negative value to positive.
// check our value should be in negative
bar=foo*-1; // multiply by -1
// return positive value;
// declare variable and assign negative value to it.
Its simply gives alert message which call our js function ConvertToPositive and return a positive value.
Wow!! we are done with method 1.
Method 2: Using Math.Abs() function.
var foo = Math.abs(-13);
var bar = Math.abs(null);
Here foo return positive value as 13, and bar result zero as it have null value.
Both method gives us desired output. But as per benchmark method 1 i.e using mathematic logic is faster then math.abs() pre-buld function.