I'm new to VB.net coding i would like to know how to round of a decimal number to the nearest integer Eg. X= (5-2/2) = 1.5 but I need only as 1.
Thank you.
CodePudding user response:
You can use the integer division operator if you just want to discard any remainder:
Dim resultValue As Integer = (5-2) \ 2
Note that this is one of the differences between VB.NET and C#, in C# the normal division operator will always apply integer division, so discard the remainder.
You have other options:
resultValue = CInt(Math.Floor((5-2) / 2))
resultValue = CInt(Math.Round((5-2) / 2, MidpointRounding.ToZero))
CodePudding user response:
Try this:
Math.Round( (5-2)/2, 0)
..and look into the options for the overload with the MidpointRounding
param, which you can set to influence rounding when the result ends with .5. Here are some of the available options:
Math.Round((5 - 2) / 2, MidpointRounding.AwayFromZero)
Math.Round((5 - 2) / 2, MidpointRounding.ToEven)
Check the documentation (or trial & error) to see which best suits your needs.
Or if you always want either the integer below or the integer above, then also check out Math.Floor
and Math.Ceiling
functions.
CodePudding user response:
I think you can use the floor function. For example, double floor(double x);
, the floor function returns the largest integer that is smaller than or equal to x.