Is it possible to round 1122.5196 to 1122?

  • A+
Category:Languages

My last goal is always to round to the nearest even intenger.

For example, the number 1122.5196 I want as result 1122. I have tried this options:

Math.Round(1122.5196d, 0, MidpointRounding.ToEven);       // result 1123 Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123 

At the end, what I would like to get it is always the nearest even intenger. For example:

  • 1122.51 --> 1122
  • 1122.9 --> 1122 (because the nearest int is 1123 but it is odd, and 1122 is nearer than 1124)
  • 1123.0 --> 1124 (the next even value, the next higher even value)

I only work with positive numbers.

And so on.

There are some method that do that or I should to implement my own method?

Thanks.

 


Try this (let's use Math.Round with MidpointRounding.AwayFromZero in order to obtain "next even value" but scaled - 2 factor):

double source = 1123.0;  // 1124.0 double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2; 

Demo:

  double[] tests = new double[] {        1.0,     1123.1,     1123.0,     1122.9,     1122.1,     1122.0,     1121.5,   };    string report = string.Join(Environment.NewLine, tests     .Select(item => $"{item,6:F1} -> {Math.Round(item / 2, MidpointRounding.AwayFromZero) * 2}"));    Console.Write(report); 

Outcome:

     1 -> 2     // In case of tie, next even value 1123.1 -> 1124 1123.0 -> 1124  // In case of tie, next even value 1122.9 -> 1122 1122.1 -> 1122 1122.0 -> 1122 1121.5 -> 1122 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: