Help with Math.abs()

Y

Yansky

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
 
V

VK

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);
 
E

Evertjan.

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]);
 
V

VK

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"
 
E

Evertjan.

VK wrote on 21 mei 2007 in comp.lang.javascript:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,428
Latest member
RosalieQui

Latest Threads

Top