Round decimal to lower number

With Decimal.Round, I can only select ToEvenand AwayFromZero, now I would like to round it always to a smaller number, i.e. as a truncation, remove the numbers that are behind the zero commas:

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

I just want all those to be rounded to 12.12345which store 5 decimal places and crop the rest. Is there a better way to do this?

+4
source share
3 answers
decimal.Truncate(value * (decimal)Math.Pow(10, 5)) / (decimal)Math.Pow(10, 5);

or simply

decimal.Truncate(value * 100000) / 100000;

should solve your problem by moving the value of 5 digits to the left, truncating and moving 5 digits back.

An example in 4 steps:

  • 1.23456 * 100000
  • 12345.6 decimal.Truncate
  • 12345 / 100000
  • 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);
+4

Math.Floor, , :

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

!

+1

, Math.Floor?

() , .

() , .

0

Source: https://habr.com/ru/post/1683169/


All Articles