10

我需要能够判断一个整数是整数还是小数。所以 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
4

6 回答 6

25
If x = Int(x) Then 
  'x is an Integer!'
Else
  'x is not an Integer!'
End If
于 2013-09-24T03:48:54.057 回答
11

您可以检查号码的地板和天花板是否相同。如果相等,那么它是一个整数,否则它会不同。

If Math.Floor(value) = Math.Ceiling(value) Then
...
Else
...
End If
于 2013-09-24T01:02:54.907 回答
5

从您需要确定它是整数还是另一种类型的事实来看,我假设该数字包含在字符串中。如果是这样可以使用Integer.TryParse方法判断该值是否为 Integer,如果成功也会将其输出为整数。如果这不是您正在做的,请使用更多信息更新您的问题。

Dim 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

编辑:

如果您使用 Decimal 或其他类型来包含您的数字,您可以使用相同的想法,n 类似这样。

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
于 2013-09-24T01:22:45.147 回答
1
Dim Num As String = "54.54"
If Num.Contains(".") Then MsgBox("Decimal")
'做一点事
于 2015-02-13T16:53:28.040 回答
1

I'm assuming that your initial value is a string.

1, First check if the string value is numeric.
2, Compare the floor and ceiling of the number. If it's the same, you have a whole number.

I prefer using extension methods.

''' <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

Example:

    Dim _myStringValue As String = "200"
    If _myStringValue.IsInteger Then
        'Is an integer
    Else
        'Not an integer
    End If
于 2017-06-09T21:01:50.103 回答
0
if x Mod 1 = 0
  'x is an Integer!'
Else
  'x is not an Integer!'
End If
于 2018-06-20T00:13:08.070 回答