0
votes

Suppose I have number 87.6 of type double here I want to round it, so I have applied C# build in method of round to get the output something like this

  double test2 = 87.6;
  Console.WriteLine(Math.Round(test2, 0));

this will generate 88 which is fine. However, I wanted to be round back to 87 my logic would be on 0.8 and not on 0.5. So for instance if my input is 87.8 then I want to get 88 and if my input is 88.7 then I want to round it to 87.

2
So subtract 0.3 and then round then? That doesn't sound difficult. - Damien_The_Unbeliever
Well, that is custom logic, so you have to write a custom code. I don't think built-in libraries will offer that possibility. - Magnetron
So what you're saying is you want to offset the value of rounding by 0.3? Just subtract 0.3 and round as you usually would. - Kieran Devlin
You can use Math.Floor(87.6) to bring it down to 87. - Rahul Raut
Be careful with negative numbers when using any of the solutions here - Emond

2 Answers

1
votes

I've got the answer from the comment section here is the logic for this

double test2 = 87.6;
test2 -= 0.3;
Console.WriteLine(Math.Round(test2, 0));

This 0.3 will make the difference

0
votes

I think this would work:

public static class RoundingExtensions {
    public static int RoundWithBreak(this valueToRound, double breakValue = .5) {
       if (breakValue <= 0 || breakValue >= 1) { throw new Exception("Must be between 0 and 1") }
       var difference = breakValue - .5;
       var min = Math.Floor(breakValue);
       var toReturn = Math.Round(breakValue - difference, 0);
       return toReturn < min ? min : toReturn;
    }
}

Consumed:

var test = 8.7;
var result = test.RoundWithBreak(.8);