【发布时间】:2016-05-31 04:36:04
【问题描述】:
我有表达式字符串:
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
【问题讨论】:
-
首先,您可以在一行中完成此操作,即
Dim result = CDbl(New DataTable().Compute(str))。至于这个问题,我想使用999999999.0会起作用。 -
对我来说,计算 API 需要一个名为 filter 的参数。你的代码怎么还能编译?
-
或者更简单:
Dim result As Double = 999999999R * 999999999R。 “R”是 Visual Basic 中Double的类型字符