我正在尝试检查字符串值(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;