我有表达式字符串:
dim str as string = "999999999 * 999999999"
我使用DataTable.Compute来计算:
dim dt as new datatable
dim result as double = 0
result = cdbl(dt.Compute(str))
我收到错误:
Value is either too large or too small for Type 'Int32'.
在这种情况下如何控制结果数据类型?
的解决方案:
此功能类似于Windows的计算器。代码如此混乱,但它起作用:)
'input = "999,999,999 x 888,888,888 + 112,365 ÷ 15 − 987,653"
Public Shared Function strCalc(ByVal input As String) As String
If input.Substring(input.Length - 1, 1) = " " Then input = input.Substring(0, input.Length - 3)
input = input.Replace("−", "-").Replace("x", "*").Replace("÷", "/").Replace(",", "")
Dim temp As Double = 0
Dim arr() As String = input.Split(" ")
If arr.Length > 1 Then
temp = New DataTable().Compute(If(arr(0).Contains("."), arr(0), arr(0) & ".0") & " " & arr(1) & " " &
If(arr(2).Contains("."), arr(2), arr(2) & ".0"), "")
If arr.Length > 3 Then
For i As Integer = 3 To arr.Length - 1 Step 2
temp = New DataTable().Compute(temp & " " & arr(i) & " " &
If(arr(i + 1).Contains("."), arr(i + 1), arr(i + 1) & ".0"), "")
Next
End If
Return temp
End If
Return input
End Function
答案 0 :(得分:1)
运行时将表达式999999999 * 999999999
视为两个整数值的乘法,并尝试将其作为对象返回,该对象是Compute
API的返回类型。这些数字相乘的输出产生一个非常大的值,该值超过可以存储在int
(System.Int32
)数据类型的变量中的最大值。
导致算术溢出异常。要给运行时提供一个提示,以便它将表达式视为两个double
数字的乘法,请使用以下代码:
dim str as string = "999999999.0 * 999999999.0"