VB2010如何判断数字是否为整数

use*_*270 8 vb.net integer numbers

我需要能够判断整数是一个整数还是有小数.因此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
Run Code Online (Sandbox Code Playgroud)

SSS*_*SSS 21

If x = Int(x) Then 
  'x is an Integer!'
Else
  'x is not an Integer!'
End If
Run Code Online (Sandbox Code Playgroud)


rcs*_*rcs 10

您可以检查号码的楼层和天花板是否相同.如果它等于,那么它是一个整数,否则它将是不同的.

If Math.Floor(value) = Math.Ceiling(value) Then
...
Else
...
End If
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以尝试 if `Math.Truncate(value) = value` (2认同)

Mar*_*all 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
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您使用 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
Run Code Online (Sandbox Code Playgroud)

  • @user2691270 [Integer](http://www.techterms.com/definition/integer) 不能有小数点,如果有小数点,它是 Decimal、Double、String 或 Single 或类似的东西。这个数字是从哪里生成的,如果是一个文本框,它可能是一个字符串。 (2认同)
  • @MarkHall:如果您对结果不感兴趣,则不需要 TryParse 的“helper”变量。您可以传递一个常量(如 0、-1、42 或其他),也可以传递“无”(整数默认为 0)。作为旁注:由于 OP 只指定了“整数”,我建议使用 BigInteger.TryParse。 (2认同)