1

I am having some trouble with a rounding issue. I have a converter to update a graphs scale to the nearest 10, based on what value comes in. the value can be either positive or negative.

I have attempted to build a math statement to round to the nearest 10 however with exceptionally small numbers it doesn't work. (numbers under 5).

the value that comes in is a double, but will be displayed in an int. any help with seeing what I did wrong would be great.

  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
                return (int)((double)value >= 0 ? 
                        (Math.Round((double)value / 10, MidpointRounding.AwayFromZero) * 10) : 
                        (Math.Abs((Math.Round((double)value / 10, MidpointRounding.AwayFromZero) * 10)) * -1));
    } 
asuppa
  • 571
  • 1
  • 11
  • 27
  • 2
    Possible duplicate of [Rounding integers to nearest multiple of 10](http://stackoverflow.com/questions/15154457/rounding-integers-to-nearest-multiple-of-10) –  Feb 10 '16 at 12:30
  • What would you expect a number of 3 to be rounded to? I´d think of zero, you not? `Round(3 / 10) = 0`. So also multiplying 10 won´t change this. – MakePeaceGreatAgain Feb 10 '16 at 12:35
  • So, you want values > 0 and < 10 to round to 10? What about 0? If that's what you want just add an `if` to check that. rounding isn't going to do what you want. – juharr Feb 10 '16 at 12:36
  • And what about 11? Should it be rounded to 10 or 20? – MakePeaceGreatAgain Feb 10 '16 at 12:36
  • anything under 0->9 needs to round to 10, 0 -> -9 needs to round to -10, Not being too familiar with the midpointrounding, using documentation it should round away from 0 regardless of what value it is however it seems to not work as I understand it – asuppa Feb 10 '16 at 12:38
  • @HimBromBeere 11 should be 20 – asuppa Feb 10 '16 at 12:38
  • @asuppa The midpoint rounding is only to determine what to do with the midpoint (5). Otherwise it rounds 1-4 down and 6-9 up. It sounds like what you want is to truncate and if there is a remainder add one (or subtract). – juharr Feb 10 '16 at 12:39
  • Then itr is a duplicate of http://stackoverflow.com/questions/921180/how-can-i-ensure-that-a-division-of-integers-is-always-rounded-up/926806 – MakePeaceGreatAgain Feb 10 '16 at 12:41
  • 1
    How should zero be once up to 10, but also down to -10? So what exactly to do with multiples of 10? Leave them or round to next 10? – MakePeaceGreatAgain Feb 10 '16 at 12:48
  • What should 0.1 and -0.1 round to? You really need to be specific about ranges here. – Matthew Watson Feb 10 '16 at 12:55

1 Answers1

4

What about this:

return value > 0 ? 
    Math.Ceiling(value / 10) * 10 : 
    Math.Ceiling(Math.Abs(value) / 10) * -10;
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111