Mode one: BigDecimal way
Double F = 3.1315;
BigDecimal B = new BigDecimal (new Double (f). toString);
Double f1 = B.setscale (3, bigdecimal.round_half_up). Doublevalue ();
Note: There must be no direct use of the new BigDecimal (double) construction method.
Instead of using the new BigDecimal (1.1315). ToString (), there will be an exact problem
Mode two: DecimalFormat way
DecimalFormat By default Roundingmode.half_even this type, and the result after format is a string
DecimalFormat df = new DecimalFormat ("#.000");
System.out.println (Df.format (New BigDecimal (1.0145));//1.014
System.out.println (Df.format (New BigDecimal (1.1315));//1.132
Mode three:
Double d = 3.1415926;
String result = String.Format ("%.2f", D);
%.2f%. Represents a floating-point type with a result of an arbitrary number of digits before the decimal point of 2 representing a two-bit decimal format.
Method Four: The traditional Math.Round rounding, to support the specified exact number of digits
Math.Round (5.2644555 *) * 0.01D;
private static Double Myround (double Number,int index) {
Double result = 0;
Double temp = Math.pow (ten, index);
result = Math.Round (number*temp)/temp;
return result;
}
Note: It is best not to use method four, because the problem of precision loss occurs when you continue to compute directly using double.
such as 0.5075 times 1000, the result is 507.49999999, so the result of the final rounding will be error.