Java - Double


Double in Java

They implements the 64-bit precision IEEE 754 floating point

Documentation: java/lang/Double

Double is a subtype of number.

Instance Creation

  • Literal
Double d = 1D;



public static double round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, RoundingMode.HALF_UP);
        return bd.doubleValue();

Setting the radix (decimal separator)

Double.parseDouble always uses a dot as the decimal separator and does not use the default locale. To interpret localized string representations of a floating-point value, use subclasses of NumberFormat.

Example, setting the radix to a , comma:

DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
// Set decimal separator
String val = "10,2";
Double doubleValue = decimalFormat.parse(val).doubleValue();


To Integer

Double d = 5.25;
Integer i = d.intValue(); // i becomes 5
// or
double d = 5.25;
int i = (int) d;

To Long

Double myDouble = 3.41;

Test / Equality

See Floating point equality for the theory of the delta.

With Junit:

// Math.abs(expected - actual) < epsilon
private static final double DELTA = 1e-15;
Assert.assertEquals(double1, double2,DELTA);

Powered by ComboStrap