jeudi 7 septembre 2017

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

I have a function that is 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?

Aucun commentaire:

Enregistrer un commentaire