是否可以检查float
是正零(0.0)还是负零(-0.0)?
我已经将float
转换为String
,并检查了第一个char
是否是'-'
,但还有其他方法吗?
发布于 2014-03-14 23:25:01
是的,除以它。1 / +0.0f
是+Infinity
,但1 / -0.0f
是-Infinity
。通过简单的比较可以很容易地找出是哪一个,所以你会得到:
if (1 / x > 0)
// +0 here
else
// -0 here
(这假设x
只能是两个零中的一个)
发布于 2014-03-14 23:27:19
您可以使用Float.floatToIntBits
将其转换为int
并查看位模式:
float f = -0.0f;
if (Float.floatToIntBits(f) == 0x80000000) {
System.out.println("Negative zero");
}
发布于 2014-03-14 23:31:24
绝对不是最好的方法。签出函数
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);
https://stackoverflow.com/questions/22409102
复制相似问题