C# Math.Round

Максим Глуховский 21 Reputation points
2021-02-24T11:18:16.567+00:00

var d = 0.0004998;//I Wont see 0,001
var d1 = 0.0005998;;//I Wont see 0,001
var d2 = 0.0004598;;//I Wont see 0,001
var d3 = 0.0004498;;//I Wont see 0,001 !!!!!!!
var d4 = 0.0004698;;//I Wont see 0,001
var D = new Double[] { d, d1, d2, d3, d4 };
foreach (var item in D) { Console.WriteLine(Math.Round(item,3,MidpointRounding.AwayFromZero)); }
Console.ReadLine();

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2021-02-24T11:48:13.947+00:00

    I would expect d, d2, d3, and d4 to round to 0. When running your code I see d1 round to 0.001

    71524-round.png

    AwayFromZero means Round to nearest mode: when a number is halfway between two others, it is rounded toward the nearest number that is away from zero.

    https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=net-5.0

    0 comments No comments

  2. Timon Yang-MSFT 9,571 Reputation points
    2021-02-28T04:27:38.813+00:00

    Although the documentation provided by vb2ae says that this enum is applicable to .Net Core and .Net Framework, it is not exactly the same in different environments.

    In .Net Framework, it has only two fields; in .Net Core, it has four.

    MidpointRounding Enum

    MidpointRounding Enum

    If you want each value to be 0.001, you can set its value to ToPositiveInfinity in .Net Core.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments