Can mathematical operators *, /, +, -, ^ be used to convert a non-zero number to 1?

dave picture dave · Oct 25, 2018 · Viewed 14.5k times · Source

I am working with software (Oracle Siebel) that only supports JavaScript expressions with operators multiply, divide, subtract, add, and XOR (*, /, -, +, ^). I don't have other operators such as ! or ? : available.

Using the above operators, is it possible to convert a number to 1 if it is non-zero and leave it 0 if it's already zero? The number may be positive, zero, or negative.

Example:

var c = 55;

var d;  // d needs to set as 1

I tried c / c , but it evaluates to NaN when c is 0. d needs to be 0 when c is 0.

c is a currency value, and it will have a maximum of two trailing digits and 12 leading digits.

I am trying to emulate an if condition by converting a number to a Boolean 0 or 1, and then multiplying other parts of the expression.

Answer

CRice picture CRice · Oct 25, 2018

Use the expression n/n^0.

If n is not zero:

 Step    Explanation
------- -------------------------------------------------------------------------------
 n/n^0   Original expression.
 1^0     Any number divided by itself equals 1. Therefore n/n becomes 1.
 1       1 xor 0 equals 1.

If n is zero:

 Step    Explanation
------- -------------------------------------------------------------------------------
 n/n^0   Original expression.
 0/0^0   Since n is 0, n/n is 0/0.
 NaN^0   Zero divided by zero is mathematically undefined. Therefore 0/0 becomes NaN.
 0^0     In JavaScript, before any bitwise operation occurs, both operands are normalized.
         This means NaN becomes 0.
 0       0 xor 0 equals 0.

As you can see, all non-zero values get converted to 1, and 0 stays at 0. This leverages the fact that in JavaScript, NaN^0 is 0.

Demo:

[0, 1, 19575, -1].forEach(n => console.log(`${n} becomes ${n/n^0}.`))