0

How can I round a double to the next .95?

Here's what I want to achieve:

4.15 should become 4.95
5.95 should become 5.95
6.96 should become 7.95

How can I achieve this?

I tried using Math.Round(), but it seems like it only supports rounding to a specific amount of decimal points. Not a specific value. I also tried this solution, but it seems like this only works for whole numbers.

Rabbid76
  • 177,135
  • 25
  • 101
  • 146
KevinMueller
  • 598
  • 3
  • 7
  • 22

3 Answers3

1

here's what I thought:

public static decimal myMethod(decimal inp)
{
    decimal flr = Math.Ceiling(inp) - 0.05m;
    decimal cll = Math.Ceiling(inp) + 1m - 0.05m;
    
    return flr >= inp ? flr : cll;
}

you probably need to make some tests though, as I only tested your values

merkithuseyin
  • 468
  • 1
  • 4
  • 14
0

There is no out-of-the-box function available, so you've to implement your own logic.

A first approach could try to follow "human logic" and look like this:

var result = (input - Math.Floor(input)) > .95
                    ? Math.Ceiling(input) + .95
                    : Math.Floor(input) + .95;

As we can see, we have to calculate the result twice, so I guess the following approach should be faster (while it really shouldn't matter and we should add a real benchmark if it matters).

var candidate = Math.Floor(input) + .95;
var result = candidate < input ? candidate + 1 : candidate;
Christoph Lütjen
  • 4,734
  • 1
  • 21
  • 31
0

It gets easier if you shift the origin: Instead of rounding a number x up to the next 0.95 you can increment it by 0.05, then round up to the next integer and finally subtract the 0.05 again:

Math.Ceiling(x + 0.05m) - 0.05m

No need for any case distinctions.

Klaus Gütter
  • 8,166
  • 5
  • 28
  • 33