About
Double in Java
They implements the 64-bit precision IEEE 754 floating point
Documentation: javase/9/docs/api/java/lang/Double.html
Double is a subtype of number.
Articles Related
Instance Creation
- Literal
Double d = 1D;
Snippet
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();
}
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();
To
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;
myDouble..longValue();
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);