May 16

The Double class contains two methods that return a representation of a floating point value according to the IEEE 754 floating-point “double format” bit layout.

The first, doubleToLongBits() does not preserve NaN and returns it as 0x7ff8000000000000L.

The second, doubleToRawLongBits() does preserve NaN and returns the representation of the actual NaN value.

The long returned by these methods can then be converted to a byte array.

byte[] array = longToByteArray(Double.doubleToRawLongBits(doubleValue));

written by objects \\ tags: , , ,

May 16

The following code can be used to extract the 8 bytes from a long value and return them as a byte array

public static byte[] longToByteArray(long data) {
    return new byte[] {
        (byte)((data >> 56) & 0xff),
        (byte)((data >> 48) & 0xff),
        (byte)((data >> 40) & 0xff),
        (byte)((data >> 32) & 0xff),
        (byte)((data >> 24) & 0xff),
        (byte)((data >> 16) & 0xff),
        (byte)((data >> 8 ) & 0xff),
        (byte)((data >> 0) & 0xff),
    };
}

written by objects \\ tags: , , , ,

Feb 23

Decimal format uses BigDecimal.ROUND_HALF_EVEN and prior to 1.6 this cannot be changed.
In 1.6 a setRoundingMethod() was added to allow the rounding strategy to be changed.

DecimalFormat df = NumberFormat.getNumberInstance();
df.setRoundingMode(1, RoundingMode.HALF_UP);
String formatted = df.format(12.345);

If you need an alternate rounding strategy prior to 1.6 then you need to use BigDecimal to do your formatting.

double d = 123.45;
BigDecimal bd = new BigDecimal(d);
bd.setScale(1, BigDecimal.ROUND_HALF_UP);
String formatted = bd.toString();

written by objects \\ tags: , , , ,