如何将.Net中的System.Decimal舍入到一些重要数字中

bra*_*ing 4 c# math decimal rounding

我有一个System.Decimal号码

0.00123456789

我希望得出3位重要数字.我预计

0.00123

行为是舍入行为而不是截断.在.Net中是否有防弹方法可以做到这一点?

xan*_*tos 5

你可以尝试这个...但我不保证任何事情......在20分钟内编写并测试并根据来自/sf/answers/110670521/的 Pyrolistical代码 有一个很大的不同之处在于他使用a long作为shifted变量(因为a double具有15-16位的精度,而a long具有18-19,所以a long就足够了),而我使用a 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;
}
Run Code Online (Sandbox Code Playgroud)

如果你不相信(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;
}
Run Code Online (Sandbox Code Playgroud)

我已经在另外20分钟内写了它(是的,我已经测试了Math.Pow((double), p)所有值的所有值-28 - +28).它似乎工作,并且它比基于doubles)的C#公式慢20%.它基于静态的pows和a BinarySearch.幸运的是,BinarySearch当它找不到一个时,已经"建议"了下一个元素:-),所以它Ceiling是免费的.


小智 -1

尝试这个 ... decimalVar.ToString ("#.##");