我有一个使用Visual Studio 2013用Visual Basic编写的单位转换器。该程序工作正常,直到用户的初始输入为小数点。我收到此错误消息:从字符串“。”转换。输入'Decimal'无效。如何让程序接受小数点作为用户的初始输入而不会导致程序崩溃?代码如下。
Private Function GetLength1(ByVal decLengthUnit1 As Decimal) As Decimal
Dim decResult1 As Decimal
If cboUnitType.SelectedItem = "Length" Then
' converts kilometer to...
If cbo1.SelectedItem = "Kilometer" Then
If cbo2.SelectedItem = "Kilometer" Then
decResult1 = txtUnit1.Text
ElseIf cbo2.SelectedItem = "Meter" Then
decResult1 = (decLengthUnit1 * 1000)
ElseIf cbo2.SelectedItem = "Centimeter" Then
decResult1 = (decLengthUnit1 * 100000)
ElseIf cbo2.SelectedItem = "Millimeter" Then
decResult1 = (decLengthUnit1 * 1000000)
ElseIf cbo2.SelectedItem = "Mile" Then
decResult1 = (decLengthUnit1 * 0.621371191)
ElseIf cbo2.SelectedItem = "Yard" Then
decResult1 = (decLengthUnit1 * 1093.613297)
ElseIf cbo2.SelectedItem = "Foot" Then
decResult1 = (decLengthUnit1 * 3280.83989)
ElseIf cbo2.SelectedItem = "Inch" Then
decResult1 = (decLengthUnit1 * 39370.07868)
End If
End If
End If
Return decResult1.ToString().Trim("0") ' this is where I convert the data back to a string with some formatting
End Function
Private Sub txtUnit1_TextChanged(sender As Object, e As EventArgs) Handles txtUnit1.TextChanged
' convert string to numeric data type
Decimal.TryParse(txtUnit1.Text, decUnit1) ' this is where I convert user input to decimal data type
' handle String.Empty, or negative sign
If txtUnit1.Text = "" OrElse txtUnit1.Text = "-" Then
txtUnit2.Text = ""
ElseIf cboUnitType.SelectedItem = "Length" Then
suppressTextBox2TextChanged = True
txtUnit2.Text = GetLength1(decUnit1)
suppressTextBox2TextChanged = False
End If
End Sub
答案 0 :(得分:2)
您的函数设置为返回十进制值
Private Function GetLength1(ByVal decLengthUnit1 As Decimal) As Decimal
您可以将其更改为As String
Private Function GetLength1(ByVal decLengthUnit1 As Decimal) As String
或者您可以更改退货
Return Ctype(decResult1.ToString().Trim("0"), DEcimal)
也可能是Decimal
期望,
而不是.
我认为它与您拥有的文化设置有关。然后,您可以更改您编写的值或执行REPLACE
Replace(decResult1.ToString().Trim("0"),".",",")
修改
您也可以尝试更改txtUnit2.Text = GetLength1(decUnit1)
将其更改为txtUnit2.Text = GetLength1(decUnit1).ToString().Trim("0")
并从函数内删除.Trim。
现在您正在修改文本框的.Text,然后使用已获取的Decimal
值。
答案 1 :(得分:0)
如果您遇到发生错误的情况,您通常可以执行以下操作:
val = 0
On Error Resume Next
val = someStatementThatMayCauseAnError
On Error Goto 0 ' turns error handling off again
对于无法解析的任何输入,这将返回0
。
当然,您也可以使用错误处理来告诉用户再试一次:
On Error Goto whoops
myString = contentsOfTextBox
val = convert(myString)
Exit Function
whoops:
MsgBox "Cannot convert " & myString & "; please try again"
End Function
最后 - 你可以明确地测试给出麻烦的字符串。但是,如果您有一个导致问题的有效字符串,则可能是您的解析函数存在问题。例如,小数点与逗号有问题吗?
答案 2 :(得分:0)
提示:在我发布您的问题之前,我正试图为我自己的学习提出一些代码进行数字验证,但我得到了这个,我不会说它已经过全面测试,但到目前为止我还没有发现错误:
Class Program
Private Shared Sub Main(args As String())
'For testing, culture string nl-BE allows , as a decimal separator
Dim d As Decimal = CheckNum(".", String.Empty)
Console.WriteLine(d.ToString())
Console.Read()
End Sub
Private Shared Function CheckNum(parm_toParseStr As String, parm_cultureName As String) As Decimal
'Convert the string sent to decimal value and raise an exception if conversion falils
'Expects string to validate and culture name (e.g. en-US). If culture name not passed, current is used
'Takes care of the missing feature in try parse, namely when a string of only "." is passed, tryparse
' does not convert it to 0.
Dim style As NumberStyles
Dim culture As CultureInfo
Dim result As Decimal
If String.IsNullOrEmpty(parm_cultureName) Then
parm_cultureName = Thread.CurrentThread.CurrentCulture.Name
End If
'for style see: http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles%28v=vs.110%29.aspx
style = NumberStyles.Number Or NumberStyles.AllowLeadingSign
culture = CultureInfo.CreateSpecificCulture(parm_cultureName)
parm_toParseStr = parm_toParseStr.Trim()
If String.IsNullOrEmpty(parm_toParseStr) Then
parm_toParseStr = "0"
End If
' Gets a NumberFormatInfo associated with the passed culture.
Dim nfi As NumberFormatInfo = New CultureInfo(parm_cultureName, False).NumberFormat
If parm_toParseStr = "+" OrElse parm_toParseStr = "-" OrElse parm_toParseStr = nfi.CurrencyDecimalSeparator Then
'+ - and decimal point
parm_toParseStr = "0"
End If
'for tryparse see: http://msdn.microsoft.com/en-us/library/ew0seb73%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
If [Decimal].TryParse(parm_toParseStr, style, culture, result) Then
Return result
Else
Throw New ArgumentNullException("Could not convert the passed value of:{0}", parm_toParseStr)
End If
End Function
End Class