0

我正在尝试检查字符串值(response.Radius)并将其四舍五入为最接近的 Int16 值(半径)。最干净和或最有效的方法是什么?我编写了以下代码,发现这是最有效的解决方案。我对么?

还有一些额外的日志信息存储在 catch 语句中。

Int16 radius; Double rDouble;
            if (Double.TryParse(response.Radius, out rDouble))
            {
                var rRounded = Math.Round(rDouble);
                if (!Int16.TryParse(rRounded.ToString(), out radius))
                {
                    if (rRounded > Int16.MaxValue)
                    {
                        radius = Int16.MaxValue;
                    }
                    else if (rRounded < Int16.MinValue)
                    {
                        radius = Int16.MinValue;
                    }
                    //response.Radius = radius.ToString();
                    Logger.Info(String.Format("Received range value {0} is outside the range of SmallInt, thus it is capped to nearest value of SmallInt i.e. {2}", Int16.MaxValue, response.Radius));
                }
                else
                {
                    Logger.Info("Response: Range " + response.Radius + " is not a valid number");
                }
            }

return response.Radius;
4

3 回答 3

2

如果你想要更小的代码,你可以使用Math.Minand Math.Max

double d = 42793.5;

double rslt = Math.Min(Int16.MaxValue, Math.Max(Int16.MinValue, d));
于 2013-08-23T13:33:51.653 回答
1

我不知道这是否是“最佳”方式(可能不是),但它应该更快(不使用异常)并且更不容易出错。

public static Int16? ToInt16(string value)
{
    double rDouble;
    if (!double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out rDouble))
    {
        // log: not a valid number
        return null;
    }
    if (rDouble < Int16.MinValue)
    {
        // log: too small
        return Int16.MinValue;
    }
    if (rDouble > Int16.MaxValue)
    {
        // log: too big
        return Int16.MaxValue;
    }

    var rounded = Math.Round(rDouble, MidpointRounding.AwayFromZero);

    return (Int16)rounded;
}

这个方法会返回一个Int16? (Nullable< Int16 >) 能够判断输入是否无效。要使用结果,您应该检查它是否有值,如果有,请使用该

于 2013-08-23T13:26:32.237 回答
0

这是我能写的最小且准确的代码。

Double rDouble;
if (Double.TryParse(response.Radius, out rDouble))
{
    var radius = Math.Round(Math.Min(Int16.MaxValue, Math.Max(Int16.MinValue, rDouble)));
    if (radius.ToString() != response.Radius))
    {
        Logger.Info(String.Format("Response: Received range value {0} is outside the range of SmallInt, thus it is capped to nearest value of SmallInt i.e. {1}", response.Radius, radius));
    }
    response.Radius = radius.ToString();
}
else
{
    Logger.Info("Response: Range " + response.Radius + " is not a valid number");
}
于 2013-08-23T14:03:16.277 回答