-2

The code below somewhat works but not rounding correctly, my goal is if a value = 1.5 round down, if 1.51 round up.

Thanks

if (!String.IsNullOrEmpty(tbSnp_Uld.Text) && !string.IsNullOrEmpty(cbSnp_Uld.Text))
{
    double d_tbSnp_Uld = Convert.ToDouble(tbSnp_Uld.Text);
    double d_cbSnp_Uld = Convert.ToDouble(cbSnp_Uld.Text);
    double result1 = Math.Ceiling(d_tbSnp_Uld / d_cbSnp_Uld);
    double d = 0; 
    int floored = (int)Math.Floor(d); 
    int ceiled = (int)Math.Ceiling(d); 
    double epsilon = 0;
    int lessThan = floored - Convert.ToInt32(Math.Abs(d - floored) < epsilon);
    int moreThan = ceiled + Convert.ToInt32(Math.Abs(d - ceiled) < epsilon);
    tbTrailer_Needed.Text = result1.ToString();
}
trashr0x
  • 6,457
  • 2
  • 29
  • 39
Booney440
  • 5
  • 7
  • What's the error? – Will Eddins Nov 14 '16 at 22:08
  • 2
    What are you asking? The title of this seems to be a list of words rather than an actual question. – Heretic Monkey Nov 14 '16 at 22:09
  • "my goal is if a value = 1.5 round down, if 1.51 round up" Well your code doesn't look like it does anything like what you want to do, but there's not a rounding option that does that - you could do `Math.Ceiling(x - 0.5)` depending on what you want to do with negative numbers. – D Stanley Nov 14 '16 at 22:16
  • basically if 50/34 = 1.47 return 1 if 52/34=1.52 return 2. anything that return more than ?.51 return 2. (3.51 should return 4) sorry if im not explaining it correctly. – Booney440 Nov 14 '16 at 22:22
  • You seem to describe the `Math.Round` function with its (now) standard mode of Bankers rounding. Why don't you use it? https://stackoverflow.com/a/7864420/3088138 – Lutz Lehmann Nov 14 '16 at 22:26
  • Possible duplicate of [Is there a way to floor/ceil based on whether the value is over 0.5 or under?](http://stackoverflow.com/questions/7864404/is-there-a-way-to-floor-ceil-based-on-whether-the-value-is-over-0-5-or-under) – Lutz Lehmann Nov 14 '16 at 22:27
  • Does it have some special meaning that all your rounding computations are for `double d=0.0`? – Lutz Lehmann Nov 14 '16 at 22:29
  • I am just learning the math has been by far the hardest for me a week on this part if this code is it unfix able by the way im doing it – Booney440 Nov 14 '16 at 22:31
  • @LutzL, round to even (banking rounding) will not work for OP's requirements in case with odd base number. He want 1.5 => 1, where rounding to even will round to 2. – Fabio Nov 14 '16 at 23:02

1 Answers1

0

Here raw sample of what you trying to accomplish. Wrote this by using TDD apporach: add tests -> make it pass.
So feel free to refactor it

public static int CustomRound(double value)
{
    int sign = Math.Sign(value);
    double absValue = Math.Abs(value);
    int absResult =  (int)Math.Round(absValue - 0.01, 0, MidpointRounding.AwayFromZero);
    return absResult * sign;
}
Fabio
  • 31,528
  • 4
  • 33
  • 72