Feb 25

You can use the setScale() method to control the rounding of a decimal value as shown in the following example:

double value = 123.456789;
BigDecimal bd = new BigDecimal(value).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bd);

written by objects \\ tags: , , ,

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: , , ,

Sep 25

Create an instance of DecimalFormat with the required format and use its format() method to format the double value. See the DecimalFormat javadoc for details on specifying format.


double d = 1.23456789;

// Use 2 decimal places

NumberFormat numberFormat =
   new DecimalFormat("#.##");

String s = numberFormat.format(d);
System.out.println(s);   // Outputs: 1.23 

written by objects \\ tags: , ,