|
|
 |
 |
 |
 |
Javascript / Client Side Development
|
 |
 |
 |
 |
 |
 |
 |
 |
Help with Math.abs()
Anyone any idea why the Math.abs() isn't working in this code? I thought it was supposed to convert negative numbers to whole numbers? var se = [-27, -27, -27]; var time = 100 if(se[0] < 0){ Math.abs(se[0]); //<-- this isn't converting it to a whole number se[0] += 1; se[0] = (se[0]/(time / 4)); }
The result I get is -1.04 when it should be 1.12
On May 21, 4:58 pm, Yansky <thegoodd@gmail.com> wrote: > Math.abs(se[0]); //<-- this isn't converting it to a whole number
Not to a whole number, but to a positive number. Whole numbers have nothing to do with Math.abs() Math.abs() is a method that returns the value of its numeric argument with sign set to positive. The argument itself doesn't change. Math.abs(se[0]); gets positive value of se[0] as requested - try alert(Math.abs(se[0])); - but as you don't store this value anywhere it gets lost. The actual value of se[0] is not affected by this operation, in your case it remains negative. Either use intermediary variable to store the value or for simple transformations: se[0] = Math.abs(se[0])/(time / 4);
On May 21, 11:21 pm, VK <schools_r@yahoo.com> wrote: > On May 21, 4:58 pm, Yansky <thegoodd @gmail.com> wrote: > but as you don't store this value anywhere > it gets lost. Ah of course. Thanks for the help. :)
Yansky wrote on 21 mei 2007 in comp.lang.javascript: > Anyone any idea why the Math.abs() isn't working in this code? I > thought it was supposed to convert negative numbers to whole numbers? > Math.abs(se[0]); //<-- this isn't converting it to a whole number
Next to what VK told you about abs, this is not returning anything, not even a positive number or zero. Try: result = Math.abs(se[0]); -- Evertjan. The Netherlands. (Please change the x'es to dots in my emailaddress)
On May 21, 6:52 pm, "Evertjan." <exjxw.hannivo@interxnl.net> wrote: > > Math.abs(se[0]); //<-- this isn't converting it to a whole number > Next to what VK told you about abs, > this is not returning anything, > not even a positive number or zero.
Why? var se = [-27, -27, -27]; var result = Math.abs(se[0]); window.alert(result); // alerts "27"
VK wrote on 21 mei 2007 in comp.lang.javascript: > On May 21, 6:52 pm, "Evertjan." <exjxw.hannivo @interxnl.net> wrote: >> > Math.abs(se[0]); //<-- this isn't converting it to a whole number >> Next to what VK told you about abs, >> this is not returning anything, >> not even a positive number or zero. > Why? > var se = [-27, -27, -27]; > var result = Math.abs(se[0]);
Because the "var result = " was not in the code of the OP. > window.alert(result); // alerts "27"
-- Evertjan. The Netherlands. (Please change the x'es to dots in my emailaddress)
|
 |
 |
 |
 |
|