我有一个System.Decimal数字
0.0012346789
我想四舍五入到3个重要数字。我期待
0.00123
其中行为是取整行为而不是截断。在.Net中有防弹的方法吗?
你可以试试这个。。。但我什么都不保证。。。在20分钟内编写并测试,基于来自https://stackoverflow.com/a/1581007/613130有一个很大的区别是,他使用long
作为shifted
变量(因为double
的精度为15-16位,而long
的精度为18-19位,所以long
就足够了),而我使用decimal
(因为decimal
的精度为28-29位)。
public static decimal RoundToSignificantFigures(decimal num, int n)
{
if (num == 0)
{
return 0;
}
// We are only looking for the next power of 10...
// The double conversion could impact in some corner cases,
// but I'm not able to construct them...
int d = (int)Math.Ceiling(Math.Log10((double)Math.Abs(num)));
int power = n - d;
// Same here, Math.Pow(10, *) is an integer number
decimal magnitude = (decimal)Math.Pow(10, power);
// I'm using the MidpointRounding.AwayFromZero . I'm not sure
// having a MidpointRounding.ToEven would be useful (is Banker's
// rounding used for significant figures?)
decimal shifted = Math.Round(num * magnitude, 0, MidpointRounding.AwayFromZero);
decimal ret = shifted / magnitude;
return ret;
}
如果你不信任(int)Math.Ceiling(Math.Log10((double)
,你可以使用这个:
private static readonly decimal[] Pows = Enumerable.Range(-28, 57)
.Select(p => (decimal)Math.Pow(10, p))
.ToArray();
public static int Log10Ceiling(decimal num)
{
int log10 = Array.BinarySearch(Pows, num);
return (log10 >= 0 ? log10 : ~log10) - 28;
}
我在另外20分钟内就写好了(是的,我已经测试了所有Math.Pow((double), p)
的所有值-28-+28)。它似乎有效,并且只比基于double
s的C#公式慢20%)。它基于一个静态的pow阵列和一个BinarySearch
。幸运的是,当BinarySearch
找不到下一个元素时,它已经"建议"了:-),所以Ceiling
是免费的。
示例:
decimal a = 1.9999M;
decimal b = Math.Round(a, 2); //returns 2
SqlDecimal具有快速计算和调整精度的方法。
public static decimal RoundToSignificantFigures(decimal num, int n)
{
SqlDecimal value = New SqlDecimal(num);
if (value.Precision > num){
int digits = num - (value.Precision - value.Scale);
value = SqlDecimal.Round(value, digits);
value = SqlDecimal.AdjustScale(value, (digits>0 ? digits : 0) - dstValue.Scale, True);
}
return value.Value;
}
试试这个。。。decimalVar.ToString ("#.##");