四舍五入小数

Round decimal number to smaller number

有了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

我只想将所有这些四舍五入到 12.12345,即保留 5 位小数,并截断剩余的小数。有更好的方法吗?

您是否正在寻找 Math.Floor

Floor(Decimal) Returns the largest integer less than or equal to the specified decimal number.

Floor(Double) Returns the largest integer less than or equal to the specified double-precision floating-point number.

decimal.Truncate(value * (decimal)Math.Pow(10, 5)) / (decimal)Math.Pow(10, 5);

或者干脆

decimal.Truncate(value * 100000) / 100000;

应该可以通过将值向左移动 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);

可以使用Math.Floor,如果在使用前修改小数位,然后return回到原来的位置,像这样:

public static decimal RoundDown(decimal input, int decimalPlaces)
{
    decimal power = (decimal) Math.Pow(10, decimalPlaces);
    return Math.Floor(input * power) / power;
}

Try it online!