I was analyzing case where DecimalFormat
rounded one BigDecimal
number and on other machine, it is truncated.
I have verified all configurations on both machines (and all are same, i assume). Only difference which i have figured out is JDK version.
Machine 1 is running on JDK1.6 . But, i have tried same with JDK1.7 on Machine 1, it is working same as with JDK1.6.
Machine 2 is running on JDK1.7
Following is the code snippet:
DecimalFormat decimalFormat = new DecimalFormat("#,###.00");
BigDecimal anObject = new BigDecimal("3.8880");
String str = decimalFormat.format(((Number)anObject).doubleValue());
System.out.println(str);
On Machine 1 Result is : 3.39
On Machine 2 result is : 3.38
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.
Use String.format("%. 2f", d); This method uses our JVM's default Locale to choose the decimal separator. For example, it would be a dot for US Locale, and for GERMANY, it would be a comma.
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.
There was a bug introduced in JDK7 on DecimalFormat
.
See this question for more information: Is inconsistency in rounding between Java 7 and Java 8 a bug?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With