In Java I have:
double x = 0.800000000000002
I want to remove 00000000000002 form x and I want x value to be 0.8.
I don't want to to use decimal format, because it converts my double to String.
I want to keep x as double.
In Java I have:
double x = 0.800000000000002
I want to remove 00000000000002 form x and I want x value to be 0.8.
I don't want to to use decimal format, because it converts my double to String.
I want to keep x as double.
A solution which avoids String formatting is this:
double
value using the desired rounding method, like Math.ceil()
, Math.floor()
or Math.rint()
.For example, if you want to round your double to two decimal places:
double x = 0.800000000000002;
System.out.println(x); // 0.800000000000002
x = Math.rint(x * 100) / 100;
System.out.println(x); // 0.8
The concept can also be used to round to quarters and similar roundings, and it can be used in research about fault calculation.
You could put this in a library, like this:
public enum Round {;
public static double round(final double x, final int decimalPrecision) {
round(x, decimalPrecision, Math::rint);
}
public static double roundUp(final double x, final int decimalPrecision) {
round(x, decimalPrecision, Math::ceil);
}
public static double roundDown(final double x, final int decimalPrecision) {
round(x, decimalPrecision, Math::floor);
}
public static double round(final double x, final int decimalPrecision, final Function<Double, Double> round) {
return round.apply(x * decimalPrecision) / decimalPrecision);
}
}
Note: Keep in mind that doubles are based on powers of 2. Not all decimal values can be represented by doubles, they're only approximated.
Warning: I have not yet tested above code.
Of course you do, but sadly 0.8
cannot be represented exactly as a double.
If you want arbitrary precision then use a class like BigDecimal
. (But in my humble opinion that class is a pig to use due to Java's lack of support for operator overloading).
The general rule for a double
is that it needs to be a dyadic rational of suitable magnitude for it to be representable perfectly. For example, 0.5, 0.25, and all integers up to the 53rd power of 2.
double number =0.76432;
double value =Double.parseDouble(new DecimalFormat("##.##").format(number));
System.out.println(value);
use according to your convinience .I guess this would be helpful .