Java - Double

1 - About

Double in Java

They implements the 64-bit precision IEEE 754 floating point

Documentation: java/lang/Double

Double is a subtype of number.

3 - Instance Creation

  • Literal

Double d = 1D;

4 - Snippet

4.1 - Round


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();
    }

4.2 - 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
decimalFormatSymbols.setDecimalSeparator(',');
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
String val = "10,2";
Double doubleValue = decimalFormat.parse(val).doubleValue();

4.3 - To

4.3.1 - To Integer


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

4.3.2 - To Long


Double myDouble = 3.41;
myDouble..longValue();

5 - 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);


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap