我正在尝试检查并将字符串值(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;
答案 0 :(得分:2)
如果您想要更小的代码,可以使用Math.Min
和Math.Max
:
double d = 42793.5;
double rslt = Math.Min(Int16.MaxValue, Math.Max(Int16.MinValue, d));
答案 1 :(得分: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&lt; Int16&gt;),以便能够判断输入是否无效。要使用结果,您应该检查它是has a value,如果是,请使用value。
答案 2 :(得分: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");
}