decimal try parse in inline code - vb.net

How to Decimal.TryParse in below line of code if value is null or empty then it should be 0 in inline coding in VB.NET
<input type="checkbox" name="ticket" id="ticket<%=y%>" title="<%=(CDec(Decimal.TryParse(late_fee)) + CDec(rs("ticket_amount")) + CDec(rs("nsf_fee")))-(CDec(rsp("TICKET_PAYMENTS")) + CDec(rsp("LATEFEE_PAYMENTS")) + CDec(rsp("NSFFEE_PAYMENTS")))%>" value="<%=rs("ticket_id")%>" checked="checked" onclick="doMath();"/>
Thanks for your advice

TryParse returns true or false based on whether conversion was successful on not.
try:
double number;
Double.TryParse(late_fee, out number);
number: "When this method returns, contains the double-precision floating-point number equivalent of the late_fee parameter, if the conversion succeeded, or zero if the conversion failed"
Use the 'number'
(CDec(number) + CDec(rs("ticket_amount")) + CDec(rs("nsf_fee")))-(CDec(rsp("TICKET_PAYMENTS")) + CDec(rsp("LATEFEE_PAYMENTS")) + CDec(rsp("NSFFEE_PAYMENTS")))

You cannot inline TryParse methods since you need to declare the variable first that will be returned from the TryParse-method. You either have to use multiple lines or create a method that returns it.
I would recommend to use variables anyway since that makes your code much more readable and that is the most important of all.
However, for what it's worth, you could make an extension which returns the decimal or a default value:
Module StringExtensions
<Runtime.CompilerServices.Extension()>
Public Function ParseDecimal(ByVal aString As String, defValue As Decimal, Optional culture As Globalization.CultureInfo = Nothing) As Decimal
Dim retVal As Decimal = defValue
If culture Is Nothing Then culture = Globalization.CultureInfo.CurrentCulture
Decimal.TryParse(aString, Globalization.NumberStyles.Any, culture, retVal)
Return retVal
End Function
End Module
Then you could inline the calculation even if i would still use multiple lines and variables to increase readability.
Dim lateFee As Decimal = late_fee.ParseDecimal(0) ' and the other variables ....

Related

Setting a string format with single quote or double format

how can I correct my method which is currently converting Bytes to Megabite into this form double 90979.32
this is my code:
Public Function BytesToMegabytes(Bytes As Double) As Double
'This function gives an estimate to two decimal
'places. For a more precise answer, format to
'more decimal places or just return dblAns
Dim dblAns As Double
dblAns = (Bytes / 1024) / 1024
BytesToMegabytes = Format(dblAns, "###,###,##0.00")
End Function
I finally need a string in the format: 90979'32.
So I need it to be a single qoute on the format instead of the decimal point.
How can I do this?
Thank you all for your help!
A number only has a format like that when it is presented to the user as a string. Until then it is just a number.
The .ToString method can take a parameter which tells it which culture to use for the formatting.
We can take advantage of that by using an existing culture and modifying it to use an apostrophe as the decimal separator:
Option Strict On
Imports System.Globalization
Module Module1
Public Function BytesToMegabytes(Bytes As Long) As String
'This function gives an estimate to two decimal
'places. For a more precise answer, format to
'more decimal places or just return dblAns
Dim dblAns As Double = (Bytes / 1024) / 1024
Dim ci = New CultureInfo("en-GB")
ci.NumberFormat.NumberDecimalSeparator = "'"
Return dblAns.ToString("###,###,##0.00", ci)
End Function
Sub Main()
Console.WriteLine(BytesToMegabytes(123445568999))
Console.ReadLine()
End Sub
End Module
Outputs:
117,726'87
You probably know the code for the culture that you want to use, so if you used that instead of "en-GB" then there would be no need to set the NumberDecimalSeparator.
If you don't want the commas for number grouping, add in
ci.NumberFormat.NumberGroupSeparator = ""
Note that the Long type is probably better if you're dealing with bytes. The type of the returned value from a function must be the same as in the declaration: using Option Strict On will help you with things like that, and you should set it as the default for new VB.NET projects.
Ref: NumberFormatInfo Class

Check string in an array

I have strings stored in an array and need to check if the 5th character of each string is a number or not. The code I used is:
If Mid(arr(i), 5, 1) = IsNumeric(True) Then
MsgBox("Number")
End If
It is giving an error:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Boolean' is not valid.
You originally tagged your question as vba, but VBA doesn't throw System.InvalidCastException, or any other exception for that matter; vb.net does.
IsNumeric(True) returns True if True is numeric. You want to verify if the string retrieved from the array is numeric; give it the string retrieved from the array as a parameter:
If IsNumeric(Mid(arr(i), 4, 1)) Then
MsgBox("Number")
End If
Your code reads like VB6/VBA though, because of this:
Imports Microsoft.VisualBasic
That namespace contains VB6-like things that you don't need to use at all. The beauty of .net is that everything is an object, so assuming the array is an array of String, you can call the actual String instance methods instead of VB6's Mid function.
Dim theFifthCharacter As String = arr(i).Substring(4, 1)
Or, because you're only interested in 1 character, and a String is itself an IEnumerable(Of Char), you can do this:
Dim theFifthCharacter As Char = arr(i)(4)
Notice the off-by-one - in .net indices start at 0, so if you want the 5th item you'll fetch index 4.
Now, if you want to see if it's numeric, you can try to parse it:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
Else
'non-numeric: digitValue contains an Integer's default value (0)
End If
Lastly, if you want a message box, use WinForms' MessageBox instead of VB6's MsgBox:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
MessageBox.Show(string.Format("Number: {0}", digitValue))
Else
'non-numeric: digitValue contains an Integer's default value (0)
MessageBox.Show("Not a number")
End If
A more correct way to do this would be:
If Char.IsDigit(arr(i)(4)) Then
Your syntax is incorrect. It should be:
If IsNumeric(Mid(arr(i), 5, 1)) Then

TryCast for string to integer in VB.NET

I do not understand at all how to use TryCast in my code, but it is something I need to use for validating user input. I have done various searches and looked at various questions on here, but no one seems to actually say how to use it, and the MSDN website doesn't seem to help at all.
Function ValidateInput(Var_In As String) As Integer
If TryCast(Var_In, Integer) = Nothing Then
Return vbNull
Else
Return Var_In
End If
End Function
The error says that
The operand must be of reference type but Integer is of value type
What is the explanation of what I have done wrong?
TryParse doesn't accept more than 10 digits so for example, an input of "12345678901" won't be accepted. How do I fix this?
Let's try to understand the differences between TryCast, Convert and TryParse.
TryCast
This function will attempt to convert one object into another type, as long as it is a reference type.
Dim MyNewObject = TryCast(MyObject, MyReferenceClass)
If IsNothing(MyNewObject) Then
MessageBox.Show("Impossible to cast")
End If
Since Integer is a value type, it will not work, so we have to figure something out...
Convert
Convert Class on MSDN
From MSDN:
Converts a base data type to another base data type.
So we can try:
Dim myInt = Convert.ToInt32(MyObject)
The problem is that it will generate an exception InvalidCastException if it's impossible to do the conversion.
TryParse
This function is trying to convert a String into something you want. And it will not generate an exception:
Dim myInt As Integer = 0
If Not Integer.TryParse(MyString, myInt) Then
MessageBox.show("This is not an integer")
End If
Limitation
Converting a String into a Integer can sometimes be tricky... If the String represents a number that is greater or lesser than Integer.MaxValue and Integer.MinValue, you will end up with no conversion...
So you can go with a Double:
Double.TryParse(MyString, MyDouble)
Or personally, if you know that it will be a number, use Decimal:
Decimal.TryParse(MyString, MyDecimal)
See Decimals on MSDN
Decimal still has a Max and Min value, according to MSDN:
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors.
Convert.ChangeType
This one is also interesting, but is a bit weird...
You are attempting to perform TryCast against an Integer, which is a value type. TryCast works only on reference types, such as (but not limited to) a Class, Object, or String type.
If you are trying to convert the input parameter to an Integer, you might try one of the methods in the Convert class, such as Convert.ToInt32() or Integer.TryParse.
Instead of TryCast, use TryParse:
Function ValidateInput(Var_In As String) As Integer
Dim iNum As Integer
If (Integer.TryParse(Var_In, iNum)) Then
Return iNum
Else
Return vbNull
End If
End Function
Much better is to use TryParse:
Function ValidateInput(Var_In As String) As Integer
Dim num as Integer
If Not Integer.TryParse(Var_In, num) Then
Return vbNull
Else
Return num
End If
End Function
I'm late to the discussion, but if anyone lands here (like I did) looking for a quick & dirty solution, here a function I'm using for simple cell validation in a DataGridView control.
Function TryTypeFit(theString As String, theType As Type, ShowError As Boolean) As Boolean
Dim TempReturn As Boolean = False
Dim TempObject As Object
Try
TempObject = Convert.ChangeType(theString, theType)
TempReturn = True
Catch ex As Exception
' didn't work
TempReturn = False
If ShowError Then
Dim eMessage As String = "Error: Value must be castable to a " & CStr(theType.Name)
MsgBox(eMessage)
End If
End Try
100:
Return TempReturn
End Function

Specifying return type of a Public Function is necessary or not?

I have a snippet here:
Dim a As Integer = 10 '<--- an integer variable inintialized with 10
a = byreferenceFun(a) '<---calling a function and assign the return value
Public Function byreferenceFun(ByVal a As Integer) '<-- function , no return type is specified
byreferenceFun = 30 ' <-- return 30 to the calling function
End Function
Their is no return type is specified in the function but it works fine and returns integer and string values;
My Question is that Specifying return type of a Public Function is necessary or not? or it is because of the reason function that should return a value?
It's not necessary in the sense that you can turn option strict off, but turning option strict off is considered by most to be a bad practice(unless of course you know exactly why you are doing it...)
If you do decide to turn option strict off and disclude the as clause on your function, then your function will return an 'Object', which is the base class that all objects inherit from, and you can cast that object to the type you are assigning it to.
The only problem is that if your function returns an object, and that object is of type "string", then when you assign the output of your function to an integer, the compiler will show no error until runtime, then you would get an invalid cast exception.
example:
Sub Calculate()
Dim result As Integer = GetCalculation()
End Sub
Function GetCalculation()
Return "hello world"
End Function
From: Function Statement (Visual Basic)
returntype - Required if Option Strict is On. Data type of the value
returned by this procedure.

In vb.net, isnumeric cannot recognize percentage string as number

I have some customized string formats of double values. I need to convert these strings to double values at some point (Note that these strings may contain error messages other than numbers). So I first check if these strings are numbers, and if yes, then convert them to double. Isnumeric works for my first customized string format. But I found that is numeric cannot recognize percentage strings. I wonder why isnumeric understands () but cannot understand %. And what is the better way to convert "(100.00)" and "50%" to doubles other than Cdbl?
Private Format As String = "###,###,###,##0.00;(###,###,###,##0.00);0" 'negative values are in the format (number)
Private rateFormat as string="p"
Dim str1 as string=-100.0.Tostring(Format) 'str1=(100.0)
Dim str2 as string=0.5.Tostring(rateFormat) 'str2=50%
Dim value1,value2 as double
If isnumeric(str1)
value1=Cdbl(str1) 'True. value1=-100.0
else
value1=Double.MinValue
End If
If isnumeric(str2)
value2=cdbl(str2) 'False.value2=Double.Minvalue
else
value2=Double.MinValue
End If
First, IsNumeric and C<whatever> generally aren't used because they can provide unexpected outputs. Typically you would use Double.TryParse or Convert.ToDouble (or whatever type) because they reliably parses numbers as you would expect; you just have to make sure it's in the right format.
Also, those methods are more efficient because you can determine if a string is a number and parse it all in one go. Just note that Parse and Convert throw exceptions when the format is wrong.
Now, as far as I know, there's know built-in way convert from percent notation. I went ahead and wrote three methods (current culture, any culture, invariant culture) that tested fine with 0.5 and -0.5 on the four possible locations of the percent symbol.
'these will return Double.NaN if they fails
'this parses based on the current culture
Public Function ParseDoublePercent(ByVal input As String) As Double
Return ParseDoublePercent(input, System.Globalization.NumberFormatInfo.CurrentInfo)
End Function
'invariant culture
Public Function ParseDoublePercentInvariant(ByVal input As String) As Double
Return ParseDoublePercent(input, System.Globalization.NumberFormatInfo.InvariantInfo)
End Function
'this parses based on a specified culture
Public Function ParseDoublePercent(ByVal input As String, ByVal provider As IFormatProvider) As Double
If String.IsNullOrEmpty(input) OrElse input.Length < 3 Then Return Double.NaN 'minimum length of string is 2 (0%)
'get some information about how the percent should be formatted
Dim format As System.Globalization.NumberFormatInfo = System.Globalization.NumberFormatInfo.GetInstance(provider)
'how this will be parsed will first depend on if it's positive or negative
Dim isNegative As Boolean = input.Substring(0, 1) = "-"
Dim percentPattern As Integer = If(isNegative, format.PercentNegativePattern, format.PercentPositivePattern)
'i'm using convert.todouble because I don't want to use NumberStyles in Double.TryParse
Try
Select Case percentPattern
Case 0 'n %, such as -50.00 %, 50.00 %
Return Convert.ToDouble(
input.Replace(" " & format.PercentSymbol, "e-" & format.PercentDecimalDigits),
provider)
Case 1 'n%, such as -50.00%, 50.00%
Return Convert.ToDouble(
input.Replace(format.PercentSymbol, "e-" & format.PercentDecimalDigits),
provider)
Case 2 '%n, such as -%50.00, %50.00
'need to do some special parsing just in case there are incorrect percent signs in the middle of the number
'dont want to just replace all of them
Return Convert.ToDouble(
input.Remove(If(isNegative, 1, 0), 1) & "e-" & format.PercentDecimalDigits, provider)
Case 3 '% n, such as '%-50.00, % 50.00
Return Convert.ToDouble(input.Remove(0, 1) & "e-" & format.PercentDecimalDigits, provider)
Case Else
Return Double.NaN 'should not happen
End Select
Catch ex As FormatException 'an exception is thrown when the string fails to parse
Return Double.NaN
End Try
End Function
isnumeric returns a Boolean value indicating whether an expression can be evaluated as a number. In your case % is not a number, so the error. Try the following code.
If isnumeric(str2.Substring(0,str2.length-2))
IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort, or an Object that contains one of those numeric types. It also returns True if Expression is a Char or String that can be successfully converted to a number.
IsNumeric returns False if Expression is of data type Date or of data type Object and it does not contain a numeric type. IsNumeric returns False if Expression is a Char or String that cannot be converted to a number.
() is, in fact, a numeric format. It's used in bookkeeping to represent negative values, instead of "-".
See http://blog.accountingcoach.com/use-of-parentheses/, or
in fact, a numeric format.In your case % is not a number, so the error.