将十进制数舍入到较小的数字

flu*_*ter 4 c# decimal .net-core .net-standard

随着Decimal.Round,我只能选择ToEvenAwayFromZero,现在我想总是舍入为较小的数字,也就是像截断,删除超出所需的小数位数:

public static void Main()
{
    Console.WriteLine("{0,-10} {1,-10} {2,-10}", "Value", "ToEven", "AwayFromZero");
    for (decimal value = 12.123451m; value <= 12.123459m; value += 0.000001m)
        Console.WriteLine("{0} -- {1} -- {2}", value, Math.Round(value, 5, MidpointRounding.ToEven),
                       Math.Round(value, 5, MidpointRounding.AwayFromZero));
}

// output
12.123451 -- 12.12345 -- 12.12345
12.123452 -- 12.12345 -- 12.12345
12.123453 -- 12.12345 -- 12.12345
12.123454 -- 12.12345 -- 12.12345
12.123455 -- 12.12346 -- 12.12346
12.123456 -- 12.12346 -- 12.12346
12.123457 -- 12.12346 -- 12.12346
12.123458 -- 12.12346 -- 12.12346
12.123459 -- 12.12346 -- 12.12346
Run Code Online (Sandbox Code Playgroud)

我只想要所有那些四舍五入12.12345,即保持5位小数,并截断剩余的小数.有一个更好的方法吗?

Fru*_*erg 5

decimal.Truncate(value * (decimal)Math.Pow(10, 5)) / (decimal)Math.Pow(10, 5);
Run Code Online (Sandbox Code Playgroud)

或者干脆

decimal.Truncate(value * 100000) / 100000;
Run Code Online (Sandbox Code Playgroud)

应该通过将值向左移5位,截断并移回5位数来解决您的问题.

4个步骤的示例:

  1. 1.23456 * 100000
  2. 12345.6 decimal.Truncate
  3. 12345 / 100000
  4. 1.2345

没有第一种方法那么简单,但在我的设备上使用字符串并将其拆分至少两倍.这是我的实现:

string[] splitted = value.ToString(CultureInfo.InvariantCulture).Split('.');
string newDecimal = splitted[0];
if (splitted.Length > 1)
{
    newDecimal += ".";
    newDecimal += splitted[1].Substring(0, Math.Min(splitted[1].Length, 5));
}
decimal result = Convert.ToDecimal(newDecimal, CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)