I just don't get what I'm doing wrong. I'm trying to calculate the number of bytes needed for BCD. The formula is rather simple: number of digits, divided by two, rounded up.
So I tried this
int halfRoundedUp = isOddNumberOfDigits ? (numberOfDigitsInParameter/2) : (numberOfDigitsInParameter/2 + 1);
or
int halfRoundedUp = isOddNumberOfDigits ? (numberOfDigitsInParameter/2) : ((numberOfDigitsInParameter/2) + 1);
or, because it was logically more sound, originally this:
int halfRoundedUp = isOddNumberOfDigits ? (numberOfDigitsInParameter/2) : ((numberOfDigitsInParameter + 1) /2);
in several variations and bracketing. Lots of brackets. It keeps returning the wrong value when the flag is set; it should add +1 after halving, but it does not.
This workaround works just fine
int halfRoundedUp = numberOfDigitsInParameter/2;
if (isOddNumberOfDigits)
halfRoundedUp ++;
but I'd like to understand what went wrong before. Can somebody explain why the above code snippets do not work as expected?
You have your arguments in the wrong order. The general for of a ternary expression is:
condition ? return_if_true : return_if_false
If the number has an odd number of digits, you'd want to divide by two and add one, so you need to flip the arguments around:
int halfRoundedUp = isOddNumberOfDigits ?
numberOfDigitsInParameter / 2 + 1 :
numberOfDigitsInParameter / 2;
EDIT:
Even though the question was about the use of the ternary operator, I must say that personally, I'd just use java.util.Math.ceil(double)
:
// note the floating point division
int halfRoundedUp = Math.ceil(numberOfDigitsInParameter / 2.0);