Rounding half down a decimal

China☆狼群 提交于 2020-11-29 11:12:27

问题


Does an equivalent of Java RoundingMode.HALF_DOWN exist in C#?

For example, I want to round 1.265 to 1.26, and 1.266 to 1.27.

If not, is there a simple way to do it?


回答1:


Have a look at Math.Round e.g.

  double[] tests = new double[] {
    1.265,
    1.266,
  };

  var demo = tests
    .Select(x => $"{x} -> {Math.Round(x, 2, MidpointRounding.AwayFromZero)}");

  var report = string.Join(Environment.NewLine, demo);

  Console.Write(report);

Outcome:

  1.265 -> 1.26
  1.266 -> 1.27



回答2:


Use the .Round method with the following constructor overload:

public static double Round (double value, int digits, MidpointRounding mode);

Calling like so:

Math.Round(value, 2, MidpointRounding.AwayFromZero);

Here's full documentation.




回答3:


You can use Math.Round

    decimal d = Convert.ToDecimal("1.266");
    Console.WriteLine(Math.Round(d, 2));

    Console.ReadLine();


来源:https://stackoverflow.com/questions/54146338/rounding-half-down-a-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!