/** * @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