Java Script equivalent to Excel Formula

265 Views Asked by At

Hi hope someone can assist.

I have the following formula in a excel spreadsheet. It calculates the difference between T40 and AB40, if it returns a negative value, it recalculates AB40 - T40 to return a positive value.

=IF(T40 > AB40, + T40 - AB40, AB40 - T40)

I have imported the spreadsheet to a PDF document, and cannot find an equivalent java script to match above.

Can anyone assist, I am now desperate and in urgent need of the information.

3

There are 3 best solutions below

3
Cerbrus On

If'm not familiar with the specifics of javascript in pdf, but something like this should work:

if(T40>AB40){
    return T40-AB40;
}else{
    return AB40-T40;
}

Or use a ternary operator like user1161318 suggested.

0
RonaldBarzell On

It can be done with an if as another response shows, but if you want to treat it as an expression, you could do it this way:

T40 > AB40 ? T40-AB40 : AB40-T40;

In Javascript:

cond ? ifTrue : ifFalse

Is an alternate way of posing an if statement that allows the whole thing to be treated as an expression, and thus be part of a formula, assigned to a variable, put in the parameter list of a function, etc... unlike if. So it's perfectly legal to do things like:

alert( cond ? ifTrue : ifFalse );
var x = cond ? ifTrue : ifFalse;

And so on, whereas you can't do that with an if block. Of course, include the expression within parenthesis if there's any chance of ambiguity (eg: it's part of a bigger formula, etc...)

I think this is closer to preserving the meaning of IF in Excel.

0
urbananimal On

You don't need an if statement you can just do:

Math.abs(T40-AB40)

To clarify this will return the absolute value of a mathematical operation so:

Math.abs(10 - 2) //returns 8

Math.abs(2 - 10) //returns 8