Simplify if-clauses when checking for range and setting default value

122 Views Asked by At

I have a function that converts a double value into the sbyte and returns its hex representation:

string convertToSByte(double num, double factor)
{

    double _Value = num * factor;

    if (_Value > 127)
    {
        _Value = 127;
    }
    else if (_Value < -127)
    {
        _Value = -127;
    }

    return Convert.ToSByte(_Value).ToString("X2");
}

The calculated _Value is supposed to be within the range of [-127 ; 127] if not then these values have to be set as default.

Question: How can these two if conditions and the setting of the default values be simplified?

EDIT:

I tried using the conditional operator ? but actually it is not much simpler (even a little harder to read) and also not really less code

ps. This question serves more of an educational purpose. To find a different way to check for ranges of a variable

1

There are 1 best solutions below

1
Titian Cernicova-Dragomir On BEST ANSWER

You could use Min/Max

string convertToSByte(double num, double factor)
{
    var value = Math.Min(127, Math.Max(-127.0, num * factor));
    return Convert.ToSByte(value).ToString("X2");
}