Penny round up in VB.Net - vb.net

Pennie round up work like this
For amount like 10.31 or 10.32 it becomes 10.30
For amount 10.33 and 10.34 it becomes 10.35
For amount 10.36 and 10.37 it becomes 10.35
For amount 10.38 and 10.39 it becomes 10.40
Please help me to achieve like this, I tried everything but no success, I will always thankful...

Here's a function that demonstrates how you can use the Mod operator to get a remainder from a number and choose what to do with it:
Public Function RoundPenny(amount As Single) As Single
Dim integerAmount As Integer = amount * 100
Dim remainder As Integer = integerAmount Mod 5
Select Case remainder
Case 0, 1, 2
integerAmount -= remainder
Case 3, 4
integerAmount += (5 - remainder)
End Select
Return integerAmount / 100
End Function

Related

Understanding Remainder operator

Just doing some basic modulo operations and trying to wrap my head around the below operations with questions marks.
0%5 // 0 - Totally understand
1%5 // 1 ?
2%5 // 2 ?
3%5 // 3 ?
4%5 // 4 ?
5%5 // 0 - Totally understand
Perhaps I'm thinking in the wrong way. For example 1/5 would return a Double of 0.2 and not a single integer so how does it return a remainder of 1?
I understand these. It makes sense but the above I can't wrap my head around.
9%4 // 1
10%2 // 0
10%6 // 4
Be great if someone could explain this. Seems I'm having a brain fart. Source of learning.
From the same Basic Operators page that you link to:
The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).
Specifically for 1 % 5:
5 doesn't fit in 1, so it fits 0 times.
This means that 1 can be described as
1 = (5 * multiplier) + remainder
Since the multiplier is 0, the remainder is 1
1 = (5 * 0) + remainder
1 = remainder
If we instead look at 6 % 5 the remainder is also 1. This is because 5 fit in 6 one time:
6 = (5 * multiplier) + remainder
6 = (5 * 1) + remainder
6-5 = remainder
1 = remainder
This / the division operator when you say 1/5 if division is in integer it'll give 0 , but this 1.0/0.5 when you make it in Double , it'll give 0.2
but % the modulo operator when you say 1%5 = 1 because you have 1 = 0*5 + 1 which means that 1 has zero number of 5 and the reminder is 1

Is there a better way to set the odds to generating a random number and controling the limits?

I am trying to do a game that has 20 rounds of play. I have assigned 0 thru 8 to represent the items in the game. I need the random number to be 90 percent of the time to be any number 0 thru 5. I need the numbers 6 and 7 to be 4 percent of the time. And, I need the 8 to be only 2 percent of the time. Below is the code I have and it works sometimes but often it generates way too many of the 6s, 7s, and 8's. The way I see the code is that it should be working most of the time correctly but does not. Is there a better way to control the random to get the percents I need to be more consistently?
' Get the random number position into array
Public Sub GetNumPositions(ByVal positions() As Integer)
' 20 rounds, each round 5 numbers
' we want 2 times (8), 4 times (6 and 7)
' 2% 8, 4% 6, 4% 7, and 90% times 0 thru 5
For i As Integer = 0 To positions.Length - 1
Dim p As Integer = rndNums.Next(100)
If p < 90 Then
positions(i) = p \ 15
ElseIf p < 94 Then
positions(i) = 6
ElseIf p < 98 Then
positions(i) = 7
Else
positions(i) = 8
End If
Next
End Sub
Your code is just fine. Here is a method to test it. It gathers some numbers and calculates their frequency:
Sub Main()
Dim count = 100000000
Dim positions(count) As Integer
Dim frequencies(9) As Integer
GetNumPositions(positions)
For Each num In positions
frequencies(num) += 1
Next
For i As Integer = 0 To 8
Console.WriteLine(i & ": " & (100.0 * frequencies(i) / count) & " %")
Next
End Sub
The result is:
0: 14.994567 %
1: 15.000016 %
2: 15.01366 %
3: 14.996542 %
4: 15.002074 %
5: 15.00325 %
6: 4.002246 %
7: 3.999337 %
8: 2.000603 %
As you can see, the frequencies match your input distribution very closely.

Penny calculator mod division

I have an assignment for a beginners VB class, and I have looked for examples for a penny calculator and have read them and tried to figure out where I am going wrong. I have a text box that takes the number of pennies you want to figure out. If you input 101 pennies it comes back with 1 dollar and 1 penny.
Strangely it works for up to 137 pennies. That comes back with 1 dollar 1 quarter 1 dime 2 pennies. If it goes to 138 or higher it just screws up. If I input 138 I get 1 dollar, 2 quarters, 1 dime, 1 nickel, 3 pennies. If I use 17 I get 1 quarter, 2 dimes, 1 nickel, 2 pennies.
Here is the arithmetic portion of my code.
DolBack = intLeftOver / 100
intLeftOver = intLeftOver Mod 100
LblDolRes.Text = DolBack.ToString
QrtBack = intLeftOver / 25
intLeftOver = intLeftOver Mod 25
LblQrtRes.Text = QrtBack.ToString
DimBack = intLeftOver / 10
intLeftOver = intLeftOver Mod 10
LblDimRes.Text = DimBack.ToString
NicBack = intLeftOver / 5
intLeftOver = intLeftOver Mod 5
LblNicRes.Text = NicBack.ToString
PenBack = intLeftOver
LblPenRes.Text = PenBack.ToString
I have tried to look my code over and look at other examples, but apparently I'm doing it a little differently. If anyone could point out the apparent major flaw in my code or my way of doing it I would appreciate it.
Further clarifying I have looked at the post at
Penny Calculator
Obviously there are a few differences with the actual arithmetic. In the link given is that because that is the only way to do it without rounding issues?
there are 100 pennies in a dollar, 25 pennies in a quarter, 10 pennies in a dime, 5 pennies in a nickel.
EDIT: Thanks for the help and pointing out my error. It's appreciated.
You're right that it's a rounding error. Use
DolBack = intLeftOver \ 100
instead of
DolBack = intLeftOver / 100
(and the same for the other ones) and you'll see a very different result.
The reason is that the / operator will do floating point division, regardless of the values either side of it, so 38/25 will yield an answer of 1.52, which rounds upwards (as you suspected) when assigned back to the variable, which is defined as an Integer. On the other hand, the \ operator will do integer division, truncating rather than rounding.
The Math.DivRem method is helpful for this kind of problem.
Dim dollars As Integer
Dim fifty As Integer
Dim quarter As Integer
Dim dime As Integer
Dim nickel As Integer
Dim pennies As Integer = 137
dollars = Math.DivRem(pennies, 100, pennies)
fifty = Math.DivRem(pennies, 50, pennies)
quarter = Math.DivRem(pennies, 25, pennies)
dime = Math.DivRem(pennies, 10, pennies)
nickel = Math.DivRem(pennies, 5, pennies)

spliting a decimal values to lower decimal in sql server

How can i split a decimal value into two decimal values.
if the decimal number which has fractional part that is less than .50 or greater than .50 .it should split in such a way that first no should end with only .00 or .50. second value should contain the remaining factorial value.
ex. 19.97 should return 19.50 & 0.47
19.47 19.00 & 0.47
You can "floor" to the highest multiple of 0.5 by multiplying by 2, calling FLOOR, then dividing by 2. From there just subtract that from the original value to get the remainder.
DECLARE #test decimal(10,7)
SELECT #test =19.97
SELECT
FLOOR(#test * 2) / 2 AS base,
#test - FLOOR(#test * 2) / 2 AS fraction
or to reduce duplication
SELECT
base,
#test - base AS fraction
FROM ( SELECT FLOOR(#test * 2) / 2 AS base )
Declare #money money
Set #money = 19.97
Select convert(int,#money - (#money % 1)) as 'LeftPortion'
,convert(int, (#money % 1) * 100) as 'RightPortion'
Observe that doubling 0.5 gives 1, which is a whole number. This leads to a simple algorithm:
Double the number
Split it into a whole and a fractional parts by using floor(x) and x-floor(x)
Divide each part separately by 2 to give you the results that you need.
Let's take your numbers as an example:
19.97 * 2 = 39.94
Whole part = 39, fractional part = 0.94
Dividing each part by 2 individually, we get
39/2 = 19.50
0.94/2 = 0.47
19.47 * 2 = 38.94
Whole part = 38, fractional part = 0.94
Dividing each part by 2 individually, we get
38/2 = 19.00
0.94/2 = 0.47
You would need to look into the MODULO operator in SQL Server.
SELECT
19.97 as myDecVal ,
19.97 % 0.5 AS decGreaterThan50,/*should return 0.47*/
19.97- (19.97 % 0.5) as roundedToNearestZeroPoint5 /*should return 19.50*/;

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.