Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DecimalFormat results in two different results on different machines [duplicate]

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

like image 399
Rohit Batta Avatar asked Jun 06 '16 07:06

Rohit Batta


People also ask

How do you make a double show with two decimal places?

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.

How do you change the decimal separator in Java?

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.

What is DecimalFormat?

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.


1 Answers

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?

like image 199
Arnaud Develay Avatar answered Sep 30 '22 14:09

Arnaud Develay