Home > Software engineering >  Inconsistent rounding after dividing an odd number by two
Inconsistent rounding after dividing an odd number by two

Time:07-27

I have a problem with rounding decimal numbers that are exactly between two integers (I mean numbers like 0.5, 1.5, 2.5, etc.). When my program has to round such a number it does not always round up or always round down as I would expect, but rounds alternately (0.5 to 0, 1.5 to 2, 2.5 to 3). Maybe I'm doing something wrong, or maybe it's because Visual Basic is programmed that way; either way, I need to get rid of this alternating rounding.

Here is some of the code, but I don't think it helps much:

Dim Input As Integer
Dim Output As Integer
Input = Val(TextBox1.Text)
Output = Input / 2
Label25.Text = Output

CodePudding user response:

First, you should turn Option Strict On globally, so you get errors about implicit narrowing conversions like this (among other important things). Then you can make an explicit decision, e.g. to always round away from zero with efficient and predictable integer math:

Dim input = Integer.Parse(TextBox1.Text)
Dim output = (input \ 2)   (input Mod 2)
Label25.Text = output.ToString()

Floating-point rounding behavior can also be controlled explicitly with Math.Round and its MidpointRounding parameter.

CodePudding user response:

The secret word is 'MidpointRounding.AwayFromZero'. As simple as that!

Math.Round(Output, 2, MidpointRounding.AwayFromZero)
  • Related