有没有可能检查一个float
是否是正零(0.0)或者负零(-0.0)?
我已经将float
转换成了String
,并且检查了第一个char
是否为'-'
,但是还有其他的方法吗?
有没有可能检查一个float
是否是正零(0.0)或者负零(-0.0)?
我已经将float
转换成了String
,并且检查了第一个char
是否为'-'
,但是还有其他的方法吗?
是的,除以它。1 / +0.0f
是 +Infinity
,但是 1 / -0.0f
是 -Infinity
。使用简单比较很容易找出它是哪一个,因此您会得到:
if (1 / x > 0)
// +0 here
else
// -0 here
(这假设x
只可能是两个零中的其中一个)
if (math.copySign (1.0, x) < 0.0) ...
- njuffamath.copySign(1.0,x)<0.0
怎样比1/x>0
更加"简单"。因为两者都不太容易理解,所以你最好使用一个专门的函数来代替它们。 - Niklas B.Float.floatToIntBits
将其转换为一个 int
,并查看二进制模式:float f = -0.0f;
if (Float.floatToIntBits(f) == 0x80000000) {
System.out.println("Negative zero");
}
(Float.floatToIntBits(f) & 0x80000000) < 0
。 - Mark Jeronimus绝对不是最好的方法。请查看该函数。
Float.floatToRawIntBits(f);
Doku:
=>文档:
/**
* Returns a representation of the specified floating-point value
* according to the IEEE 754 floating-point "single format" bit
* layout, preserving Not-a-Number (NaN) values.
*
* <p>Bit 31 (the bit that is selected by the mask
* {@code 0x80000000}) represents the sign of the floating-point
* number.
...
public static native int floatToRawIntBits(float value);
Double.equals
方法在Java中区分±0.0。(还有Float.equals
方法。)
我有点惊讶没有人提到这些方法,因为它们对我来说似乎比目前给出的任何方法都更清晰明了!
Math.min
的使用方法类似于 Jesper 提出的方法,但更加清晰明了。private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);
当一个浮点数为负数(包括-0.0
和-inf
)时,它使用与负整数相同的符号位。这意味着您可以将整数表示与0
进行比较,无需知道或计算-0.0
的整数表示:
if(f == 0.0) {
if(Float.floatToIntBits(f) < 0) {
//negative zero
} else {
//positive zero
}
}
这篇回答相对于被接受的回答多了一个分支,但我认为没有16进制常量更容易阅读。
如果你的目标只是把-0看作负数,你可以省略外部的if
语句:
if(Float.floatToIntBits(f) < 0) {
//any negative float, including -0.0 and -inf
} else {
//any non-negative float, including +0.0, +inf, and NaN
}
对于负数:
new Double(-0.0).equals(new Double(value));
正向情况:
new Double(0.0).equals(new Double(value));
只需使用Double.compare(d1,d2)。
double d1 = -0.0; // or d1 = 0.0
if ( Double.compare (d1, 0.0) < 0 )
System.out.println("negative zero");
else
System.out.println("positive zero");