我需要能够判断一个整数是否为整数或者它是否有小数位。因此,13将是一个整数,而23.23将是一个带有小数位的数字。
就像这样;
If 13 is a whole number then
msgbox("It's a whole number, with no decimals!")
else
msgbox("It has a decimal.")
end if
If x = Int(x) Then
'x is an Integer!'
Else
'x is not an Integer!'
End If
您可以检查一个数字的整数部分和上下取整是否相等。如果相等,则为整数,否则不是。
If Math.Floor(value) = Math.Ceiling(value) Then
...
Else
...
End If
Math.Truncate(value) = value
来判断。 - Stef GeyselsDim number As String = 34.68
Dim output As Integer
If (Integer.TryParse(number, output)) Then
MsgBox("is an integer")
Else
MsgBox("is not an integer")
End If
编辑:
如果您正在使用十进制或其他类型来包含您的数字,您可以使用相同的思路,类似于这样。
Option Strict On
Module Module1
Sub Main()
Dim number As Decimal = 34
If IsInteger(number) Then
MsgBox("is an integer")
Else
MsgBox("is not an integer")
End If
If IsInteger("34.62") Then
MsgBox("is an integer")
Else
MsgBox("is not an integer")
End If
End Sub
Public Function IsInteger(value As Object) As Boolean
Dim output As Integer ' I am not using this by intent it is needed by the TryParse Method
If (Integer.TryParse(value.ToString(), output)) Then
Return True
Else
Return False
End If
End Function
End Module
Dim Num As String = "54.54" 如果 Num 包含 "." 则 MsgBox("Decimal") '做些什么
''' <summary>
''' Is Numeric
''' </summary>
''' <param name="p_string"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()>
Public Function IsNumeric(ByVal p_string As String) As Boolean
If Decimal.TryParse(p_string, Nothing) Then Return True
Return False
End Function
''' <summary>
''' Is Integer
''' </summary>
''' <param name="p_stringValue"></param>
''' <returns></returns>
<Extension()>
Public Function IsInteger(p_stringValue As String) As Boolean
If Not IsNumeric(p_stringValue) Then Return False
If Math.Floor(CDec(p_stringValue)) = Math.Ceiling(CDec(p_stringValue)) Then Return True
Return False
End Function
例子:
Dim _myStringValue As String = "200"
If _myStringValue.IsInteger Then
'Is an integer
Else
'Not an integer
End If
if x Mod 1 = 0
'x is an Integer!'
Else
'x is not an Integer!'
End If