Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with Math.Round() in VB.Net?

Tags:

vb.net

I have encountered a weird case in Math.Round function in VB.Net

Math.Round((32.625), 2)

Result : 32.62

Math.Round((32.635), 2)

Result : 32.64

I need 32.63 but the function is working in different logic in these cases.

I can get the decimal part and make what I want doing something on it. But isn't this too weird, one is rounding to higher, one is rounding to lower.

So how can I get 32.63 from 32.625 without messing with decimal part ? (as the natural logic of Maths)

like image 894
Mtok Avatar asked Feb 12 '13 14:02

Mtok


People also ask

What does Math round do in VB?

Rounds a value to the nearest integer or to the specified number of fractional digits.

How do I round a value in VB net?

The basic function for rounding up is Math. Ceiling(d), but the asker specifically wanted to round up after the second decimal place. This would be Math. Ceiling(d * 100) / 100.

How do you round decimals in VB net?

The Decimal. Round method will do the trick for you. You can specify the number of decimal places. Note that this doesn't round down as Math.

Why do we use Math round?

round() is used round of the decimal numbers to the nearest value. This method is used to return the closest long to the argument, with ties rounding to positive infinity.


1 Answers

Math.Round uses banker's rounding by default. You can change that by specifying a different MidPointRounding option. From the MSDN:

Rounding away from zero

Midpoint values are rounded to the next number away from zero. For example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8, and -3.85 rounds to -3.9. This form of rounding is represented by the MidpointRounding.AwayFromZero enumeration member. Rounding away from zero is the most widely known form of rounding.

Rounding to nearest, or banker's rounding

Midpoint values are rounded to the nearest even number. For example, both 3.75 and 3.85 round to 3.8, and both -3.75 and -3.85 round to -3.8. This form of rounding is represented by the MidpointRounding.ToEven enumeration member.

Rounding to nearest is the standard form of rounding used in financial and statistical operations. It conforms to IEEE Standard 754, section 4. When used in multiple rounding operations, it reduces the rounding error that is caused by consistently rounding midpoint values in a single direction. In some cases, this rounding error can be significant.

So, what you want is:

Math.Round(32.625, 2, MidpointRounding.AwayFromZero)
Math.Round(32.635, 2, MidpointRounding.AwayFromZero)

As others have mentioned, if precision is important, you should be using Decimal variables rather than floating point types. For instance:

Math.Round(32.625D, 2, MidpointRounding.AwayFromZero)
Math.Round(32.635D, 2, MidpointRounding.AwayFromZero)
like image 161
Steven Doggart Avatar answered Sep 29 '22 07:09

Steven Doggart