Rounding in Java--several types of rounding

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.