Java rounding solutions and considerations with BigDecimal

Source: Internet
Author: User

/**     * @Description: Rounding leave 2 decimal places     * @param valueName     * @return */public    static Double formateDouble45 (Double D) {        if (d = = null) {            return 0d;        }        BigDecimal   B   =   new   BigDecimal (d);        Double   f   =   B.setscale (2,   bigdecimal.round_half_up). Doublevalue ();        return f;    } Above is a method that I wrote before to round up 2 decimal places, and recently found to be problematic for example: 2.555 get is 2.55 instead of the expected 2.56 improvements as follows: <pre name= "code" class= "java" >    /** * @ Description: Rounding left 2 decimal places * @param valueName * @return */public static Double formateDouble45 (Object D) {if (d = = null) {return 0d;} BigDecimal   B   =   new   BigDecimal (d.tostring ());d ouble   F   =   B.setscale (2,   BIGDECIMAL.ROUND_HALF_UP). Doublevalue (); return f;}

The test found that all normal rounding would be possible if the string type was used when building bugdecimal.
The specific reason is unknown.

Java rounding out solutions and considerations by BigDecimal

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.