Problem: some numbers are positive some are not. Here is my function to convert negative numbers to positive ones and leave positive numbers untouched. Is there a better way of doing it in JavaScript?
function intAbs(integer) {
if(isNaN(integer)) {
throw 'NaN';
}
if(parseInt(integer, 10) !== integer) {
throw 'Not an integer';
}
n = integer * integer;
var x = 1;
var e = 1;
while(!(e < 0.1 && e > -0.1)) {
x = (n / x + x) / 2;
e = n - x * x;
}
return parseInt(x);
}
Update: I don't think this question is a duplicate. I know how to get the absolute value of an integer without Math.abs()
. You can see in this question. I have already accepted the answer which states "Yes, there is a better way" and it's not ambiguous.
Update #2: This question is marked as a duplicate of Get the absolute value of a number in Javascript, but this does not address problem if(is there a better way of calculating abs than exactly this algorithm)
. I give up.