Math.round: round number by conditions - vb.net

I am trying to round a number by the next things:
number with unit digits between 5-10 will be rounded to the nearest 10*x:
(for example: 5->10, 6->10, 27->30, 40->40, 56->60, etc).
number with unit digits between 1-4 will be rounded to 0:
(for example: 4->0, 11->10, 12->10, 20->20, etc).
I want to write it bu Math.Round function.
Meantime, I did it without it:
Dim rest As Integer = r Mod 10
' round up
If rest >= 5 Then
r = r + (10 - rest)
Else ' round down
r = r - rest
End If
Any help appreciated!

Very simple to do with Math.Round
Dim roundedDecade as Double, originalNumber as Double
:
roundedDecade = Math.Round(originalNumber / 10, MidpointRounding.AwayFromZero) * 10
If you want to force the use of integers, just use CDbl and CInt to force some conversions.
Dim roundedDecade as Integer, originalNumber as Integer
:
roundedDecade = CInt(Math.Round(CDbl(originalNumber) / 10, MidpointRounding.AwayFromZero) * 10)

Related

VB.net Round off Decimal number to the nearest integer

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.
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))
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.
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.

VBA random numbers produces a repeating sequence at regular intervals

This code is supposed to generate a sequence of 10,000 random numbers in VBA. For some reason I am only able to produce a unique sequence of length 5842, and then it repeats. But, and this is the strangest part, each time I run the code, the sequence starts in a different place. For example in one run, the elements following element 2660 are the same as those following element 8502 (8502-2660= 5842). The next run, I get a sequence that repeats following elements 3704 and 9546 (9546-3704=5842). And so on.
Function NormRand() As Double
' NormRand returns a randomly distributed drawing from a
' standard normal distribution i.e. one with:
' Average = 0 and Standard Deviation = 1.0
Dim fac As Double, rsq As Double, v1 As Double, v2 As Double
Static flag As Boolean, gset As Double
' Each pass through the calculation of the routine produces
' two normally-distributed deviates, so we only need to do
' the calculations every other call. So we set the flag
' variable (to true) if gset contains a spare NormRand value.
If flag Then
NormRand = gset
' Force calculation next time.
flag = False
Else
' Don't have anything saved so need to find a pair of values
' First generate a co-ordinate pair within the unit circle:
Do
v1 = 2 * Rnd - 1#
v2 = 2 * Rnd - 1#
rsq = v1 * v1 + v2 * v2
Loop Until rsq <= 1#
' Do the Math:
fac = Sqr(-2# * Log(rsq) / rsq)
' Return one of the values and save the other (gset) for next time:
NormRand = v2 * fac
gset = v1 * fac
flag = True
End If
End Function
For some reason I am only able to produce a unique sequence of length
5842, and then it repeats. But, and this is the strangest part, each
time I run the code, the sequence starts in a different place
That's by design and well known - that's why the number generation is labelled pseudo random and not random.
By the way, I notice that you are multiplying the two values. That may not be a good idea - as mentioned here.
In your function, you may try to replace Rnd with RndDbl:
Public Function RndDbl(Optional ByRef Number As Single) As Double
' Exponent to shift the significant digits of a single to
' the least significant digits of a double.
Const Exponent As Long = 7
Dim Value As Double
' Generate two values like:
' 0.1851513
' 0.000000072890967130661
' and add these.
Value = CDbl(Rnd(Number)) + CDbl(Rnd(Number) * 10 ^ -Exponent)
RndDbl = Value
End Function
and then modify your code to include a dynamic seed by calling Timer:
Do
v1 = 2 * RndDbl(-Timer) - 1#
v2 = 2 * RndDbl(-Timer) - 1#
rsq = v1 + v2
Loop Until rsq <= 1#
The generated values will still not be true random, but should not take form of a repeated sequence.

Rounding a variable to an integer

I have a calculation like this: 3 * 12300 / 160. The result is: 230.625. But I just want the integer part, 230.
In C, this can be done using something like this: int MyVar = (int)3*12300/160;
Is there a way in VBA (With MS-Access) for force the result to be an integer?
You can round down using the Int or Fix functions.
Since you know the result you want is a whole number, you should store the result in a variable of type Long (or Integer if you're absolutely certain it will always be smaller than 32768).
Dim l As Long
l = Int(3 / 160 * 12300) ' <~~~~ Yes, I switched the numbers around on purpose!*
MsgBox "l = " & l
* Why did I switch the numbers around? Because the expression 3 * 12300 / 160 will throw an error in VBA. Read here why: Overflow when multiplying Integers and assigning to Long

Vb.net number truncate. How to do this?

I wanna round "2.765467..." number to "2.70".
How can i do that?
İ tried Math.round or math.floor but not working:(
Anyone can send a code for vb.net?
It sounds like what you want to do is truncate, not round. Try this:
Dim decTemp = (10 ^ NumberOfPlaces)
Return CDec(Fix(ToTruncate * decTemp) / decTemp)
Where ToTruncate is the number you'd like to truncate, and NumberOfPlaces is the number of decimal places you want to truncate to. In your case:
Dim ToTruncate As Decimal = 2.765467D
Dim NumberofPlaces as Integer = 1
Dim decTemp = (10 ^ NumberOfPlaces)
Return CDec(Fix(ToTruncate * decTemp) / decTemp)

Rounding a number to the nearest 5 or 10 or X

Given numbers like 499, 73433, 2348 what VBA can I use to round to the nearest 5 or 10? or an arbitrary number?
By 5:
499 -> 500
2348 -> 2350
7343 -> 7345
By 10:
499 -> 500
2348 -> 2350
7343 -> 7340
etc.
It's simple math. Given a number X and a rounding factor N, the formula would be:
round(X / N)*N
Integrated Answer
X = 1234 'number to round
N = 5 'rounding factor
round(X/N)*N 'result is 1235
For floating point to integer, 1234.564 to 1235, (this is VB specific, most other languages simply truncate) do:
int(1234.564) 'result is 1235
Beware: VB uses Bankers Rounding, to the nearest even number, which can be surprising if you're not aware of it:
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
Thank you everyone.
To round to the nearest X (without being VBA specific)
N = X * int(N / X + 0.5)
Where int(...) returns the next lowest whole number.
If your available rounding function already rounds to the nearest whole number then omit the addition of 0.5
In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.
The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.
'Example: Round 499 to nearest 5. You would use the ROUND() FUNCTION.
a = inputbox("number to be rounded")
b = inputbox("Round to nearest _______ ")
strc = Round(A/B)
strd = strc*B
msgbox( a & ", Rounded to the nearest " & b & ", is" & vbnewline & strd)
For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)
Multiples of 5 or x can be done simply by dividing before and multiplying after the round.
If you want to round and keep decimal places, Math.round(n, d) would work.
Here is our solution:
Public Enum RoundingDirection
Nearest
Up
Down
End Enum
Public Shared Function GetRoundedNumber(ByVal number As Decimal, ByVal multiplier As Decimal, ByVal direction As RoundingDirection) As Decimal
Dim nearestValue As Decimal = (CInt(number / multiplier) * multiplier)
Select Case direction
Case RoundingDirection.Nearest
Return nearestValue
Case RoundingDirection.Up
If nearestValue >= number Then
Return nearestValue
Else
Return nearestValue + multiplier
End If
Case RoundingDirection.Down
If nearestValue <= number Then
Return nearestValue
Else
Return nearestValue - multiplier
End If
End Select
End Function
Usage:
dim decTotal as Decimal = GetRoundedNumber(CDec(499), CDec(0.05), RoundingDirection.Up)
Simply ROUND(x/5)*5 should do the job.
I cannot add comment so I will use this
in a vbs run that and have fun figuring out why the 2 give a result of 2
you can't trust round
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
something like that?
'nearest
n = 5
'n = 10
'value
v = 496
'v = 499
'v = 2348
'v = 7343
'mod
m = (v \ n) * n
'diff between mod and the val
i = v-m
if i >= (n/2) then
msgbox m+n
else
msgbox m
end if
Try this function
--------------start----------------
Function Round_Up(ByVal d As Double) As Integer
Dim result As Integer
result = Math.Round(d)
If result >= d Then
Round_Up = result
Else
Round_Up = result + 1
End If
End Function
-------------end ------------
I slightly updated the function provided by the "community wiki" (the best answer), just to round to the nearest 5 (or anything you like), with this exception : the rounded number will NEVER be superior to the original number.
This is useful in cases when it is needed to say that "a company is alive for 47 years" : I want the web page to display "is alive for more than 45 years", while avoiding lying in stating "is alive for more than 50 years".
So when you feed this function with 47, it will not return 50, but will return 45 instead.
'Rounds a number to the nearest unit, never exceeding the actual value
function RoundToNearestOrBelow(num, r)
'#param num Long/Integer/Double The number to be rounded
'#param r Long The rounding value
'#return OUT Long The rounded value
'Example usage :
' Round 47 to the nearest 5 : it will return 45
' Response.Write RoundToNearestBelow(47, 5)
Dim OUT : OUT = num
Dim rounded : rounded = Round((((num)) / r), 0) * r
if (rounded =< num) then
OUT = rounded
else
OUT = rounded - r
end if
'Return
RoundToNearestOrBelow = OUT
end function 'RoundToNearestOrBelow
To mimic in Visual Basic the way the round function works in Excel, you just have to use:
WorksheetFunction.Round(number, decimals)
This way the banking or accounting rounding don't do the rounding.