If Statements using Decimal Data Type - vb.net

I have an If statement in which I need to check if a decimal number is less than or equal to 4. I planned to do so using this code, which I will paste for some clarity:
Dim handicap As New List(Of Decimal)
For i = 0 To handicap.Count - 1
If handicap.Item(i) <= 4 Then
....
End If
Next i
However, I cannot compare the decimal to the integer type. Is there a way I can do this?

Try If handicap.Item(i) <= Convert.ToDecimal(4) Then
or If handicap.Item(i) <= 4D Then
Read more on https://msdn.microsoft.com/en-us/library/xtba3z33.aspx

Related

Convert integer value to fractional value (decimal)

Looking for a way to convert a positive number (integer) from e.g. 123 to 0.123 without using strings. Can be any size integer. Not concerned about negative values.
Dim value As Integer = 123
Dim num As Decimal = "." & value.ToString
It seems simple but I'm not sure how to do it using math. How can I convert without using strings?
You can get the number of digits using Log10. I think the best way is thusly:
Dim value = 123 'Or whatever other value
Dim digitCount = Math.Floor(Math.Log10(Math.Abs(value))) + 1
Dim result = value * CDec(10 ^ (-digitCount))
You need to use Floor rather than Ceiling in order to get the right result for 0, 10, 100, etc.
Here's one method:
Dim value As Integer = 123
Dim num As Decimal = value
While Math.Abs(num) >= 1
num = num / 10
End While
The Math.Abs takes care of negatives, so you could remove it as you say you're not concerned with them.
This also works:
Dim value as Integer = 123
Dim num as Decimal = value
num /= 10 ^ Math.Ceiling(Math.Log10(value))
It's a little harder to see what's going on initially, but it basically finds the next power of 10 that is above the number, and divides by the 10^(that power)
Edit As per Craigs answer Math.Floor then add one works better than Math.Ceiling thus:
Dim value as Integer = 123
Dim num as Decimal = value
num /= 10 ^ (Math.Floor(Math.Log10(value)) + 1)
Edit
I just did a quick performance comparison, and on my PC doing the While loop took 851ms, and the Log10 method took 158ms. That's for 1,000,000 iterations of each.

Format number in datagridview- If integer then F0, if decimal then F

I need to format all numbers in a datagridview.
If the number is a whole number then do not show the decimal point and if the number has a fraction then do show the decimal point.
I have achieved this by looping through each column and checking if the content is a double/single/decimal and then looping through each row in those columns to check each value whether the number is whole or has a fraction.
But this takes a long time for the application to process since i might have 2000 rows or more with 5 or more columns being double/single/decimal.
I can't find a standard format which does this.
Can anybody help?
dgv.SuspendLayout()
For i = 0 To dgv.Columns.Count - 1
If dgv.Columns(i).ValueType = GetType(Double) Or dgv.Columns(i).ValueType = GetType(Single) Or dgv.Columns(i).ValueType = GetType(Decimal) Then
'check If the number has a fraction
For u = 0 To dgv.Rows.Count - 1
If Not IsDBNull(dgv.Rows(u).Cells(i).Value) Then
If dgv.Rows(u).Cells(i).Value Mod 1 <> 0 Then
'number has a fraction
dgv.Rows(u).Cells(i).Style.Format = "F"
Else
'number is an integer
dgv.Rows(u).Cells(i).Style.Format = "F0"
End If
End If
Next
End If
Next
dgv.ResumeLayout()
Using the Datagridview.CellFormatting event seemed to solve the issue - Thanks Jimi. I just can't understand the difference between using the event and setting the format in a loop after populating the datagridview

Visual Basic programming

I am new to the programing world and I am stuck on the below problem please could you assist me
Write a Visual Basic.net function to calculate the sum of all the numbers in an input field. For example, if the input string is: "ICT2611", then the numbers included in this string are: 2, 6, 1, 1 and their sum is therefore, 2+6+1+1 = 10
The below should solve your problem, it uses Regex to find any matches in the provided string to the expression (numbers 1 - 9), and then iterates through them tallying them up as it goes.
Public Function SumOfString(str As String) As Integer
Dim total As Integer = 0
For Each i As Match In Regex.Matches(str, "[1-9]")
total += i.Value
Next
Return total
End Function
Alternatively the same thing could be achieved like this, this just iterates through each character in the string and then checks to see if it's a digit. If it is a digit then it'll tally it up.
Public Function SumOfString(str As String) As Integer
Dim total As Integer = 0
For Each i As Char In str
If Char.IsDigit(i) Then total += Integer.Parse(i)
Next
Return total
End Function

How can I test if a user input is a decimal with no more than 2 digits after the decimal place?

I'm supposed to make a banking software form that allows a user to create accounts and make deposits and withdrawals for any account. But I cannot figure out how to make it accept an integer, a decimal with only one digit after the dot, or a decimal with the first digit after the dot being a 0.
Dim x As Decimal = Decimal.Parse(txtAmount.Text)
If (txtAmount.Text.IndexOf(".") <> -1 And txtAmount.Text.Substring(txtAmount.Text.IndexOf("." + 1)).Length > 2) Then
MessageBox.Show("No fractions of a penny")
Exit Sub
End If
Dim a As CAccount = lbxCustomers.SelectedItem
a.deposit(x)
Anyone know what I'm doing wrong?
Using the tryparse as suggested is most definitely a good starting point. One simple way to disregard extra digits is with the Truncate method:
Dim x As Decimal
If Decimal.TryParse(txtAmount.Text, x) Then
x = Decimal.Round(x * 100) / 100
Else
MessageBox.Show("Only valid numbers please")
End If
This will leave x with only a maximum of 2 decimal places. This also rounds the resulting value according to the value in the extra digits. This is useful for the Decimal type since it is prone to rounding errors and this will even them out.
You can compare the current value with the rounded value. If the two are equal, you know there isn't more digits. This won't work if you want to also limit zeros (2.0000 will pass).
Dim val As Decimal
val = 2.2345
If val * 100 = Math.Floor(val * 100) Then
' Has 2 or less digit
Else
' Has more than 2 digit
End If

How do I cope with rounding errors on doubles in vb.net?

I'm trying to balance a set of currency values using vb.net. The totals for both these values is cast as a double. I'm getting rounding errors in some situations.
What's the best way to avoid this? Is there a type I can use in preference to double? How do I round the resultant value to two decimal places?
Here's my code - I probably don't need to show it, but just in case.
Dim nInvValue As Double
Dim nCreditValue As Double
For Each oReferenceItem In oMatchInvoices
Dim nUnallocated As Double = oReferenceItem.DocumentOutstandingValue - oReferenceItem.DocumentAllocatedValue
If ((nUnallocated <> 0) And (sReferenceValue = oReferenceItem.InstrumentNo)) Then
iCount = iCount + 1
If (oReferenceItem.IsDebit) And (nUnallocated > 0) Then
nInvValue = nInvValue + nUnallocated
InvoiceList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
If (oReferenceItem.IsCredit) And (nUnallocated < 0) Then
nCreditValue = nCreditValue - nUnallocated
CreditList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
End If
Next
For financial calculations I believe that the current wisdom is to use Decimals instead of Doubles.
You might be interested in this discussion Decimal Vs. Double.
Try using the Decimal type.
MSDN - Decimal