有没有一种方法或快速方式可以在Java中检查一个数字是否为整数(属于Z域)?
我考虑过可能将其从四舍五入的数字中减去,但我没有找到任何可以帮助我的方法。
我应该在哪里检查? Integer Api?
有没有一种方法或快速方式可以在Java中检查一个数字是否为整数(属于Z域)?
我考虑过可能将其从四舍五入的数字中减去,但我没有找到任何可以帮助我的方法。
我应该在哪里检查? Integer Api?
快速而简单...
if (x == (int)x)
{
...
}
编辑:假设x已经是某种其他数字形式。如果您正在处理字符串,请查看 Integer.parseInt
。
再举一个例子 :)
double a = 1.00
if(floor(a) == a) {
// a is an integer
} else {
//a is not an integer.
}
在这个例子中,可以使用 ceil 函数并且具有完全相同的效果。/**
* Check if the passed argument is an integer value.
*
* @param number double
* @return true if the passed argument is an integer value.
*/
boolean isInteger(double number) {
return number % 1 == 0;// if the modulus(remainder of the division) of the argument(number) with 1 is 0 then return true otherwise false.
}
如果你在讨论浮点数值,由于其格式的特性,你必须非常小心。
我知道的最好方法是决定一些epsilon值,比如0.000001f,然后像这样做:
boolean nearZero(float f)
{
return ((-episilon < f) && (f <epsilon));
}
那么
if(nearZero(z-(int)z))
{
//do stuff
}
本质上,您正在检查z和z的整数部分是否在某些公差内具有相同的大小。这是必要的,因为浮点数本质上是不精确的。
但是请注意:如果您的浮点数的大小大于 Integer.MAX_VALUE
(2147483647),则此方法可能会失效,您应该知道,在那个值以上的浮点数上不可能检查整数部分。
通过 Z,我假设你指的是整数,即3、-5、77,而不是3.14、4.02等。
正则表达式可能会有所帮助:
Pattern isInteger = Pattern.compile("\\d+");
double x == 2.15;
if(Math.floor(x) == x){
System.out.println("an integer");
} else{
System.out.println("not an integer");
}
我认为你可以使用Math.ceil()
方法来验证x
是否为整数。这是因为Math.ceil
或Math.floor
将x
四舍五入到最近的整数(比如y
),如果x==y
,那么我们原来的`x'就是一个整数。
所有给出的解决方案都很好,但是它们中的大多数可能会在静态代码分析(例如SONAR)中出现问题:“浮点数不应该进行相等性测试”(请参见https://jira.sonarsource.com/browse/RSPEC-1244)。
我假设应该被测试的输入是double类型,而不是字符串。
作为一种解决方法,我测试数字是否不是整数:
public boolean isNotInteger(double x) {
return x - Math.floor(x) > 0;
}
if((number%1)!=0)
{
System.out.println("not a integer");
}
else
{
System.out.println("integer");
}
double x = 1.1;
int count = 0;
if (x == (int)x)
{
System.out.println("X is an integer: " + x);
count++;
System.out.println("This has been added to the count " + count);
}else
{
System.out.println("X is not an integer: " + x);
System.out.println("This has not been added to the count " + count);
}
int x = 3;
if(ceil(x) == x) {
System.out.println("x is an integer");
} else {
System.out.println("x is not an integer");
}
ceil(int)
函数,这是无用的。另外,如果 x
已经是一个 int
,那么这个检查有什么意义呢? - randers