Java 6 - Creating and detecting the first Double v

2019-06-06 04:54发布

I would like to create the Double whose value is closest to, but greater than, Float.MAX_VALUE.

I've just written a question similar to this but for Double and Long.MAX_VALUE, see here.

How can I repeat the conversion for Double and Float.MAX_VALUE using the standard Java 6 API?

My attempt is below, but is incorrect it seems:

Long longValue = Long.valueOf(Float.floatToIntBits(Float.MAX_VALUE));
Double value = Double.longBitsToDouble(Double.doubleToLongBits(longValue)+1);

if (value < -Float.MAX_VALUE || value > Float.MAX_VALUE) {
    // Code here should execute but does not.
}

Sincere thanks.

2条回答
ら.Afraid
2楼-- · 2019-06-06 05:16
Double val = (double)Float.MAX_VALUE;
val += Math.ulp(val);

This may also work (correction of your example), but not entirely sure:

Double val = Double.longBitsToDouble(Double.doubleToLongBits(Float.MAX_VALUE)+1);
查看更多
beautiful°
3楼-- · 2019-06-06 05:20
Math.nextUp((double) Float.MAX_VALUE);

It's not only equivalent to the most efficient solution, but...it makes it pretty obvious what result you should expect.

查看更多
登录 后发表回答