1

I have a program where I am generating two double numbers by adding several input prices from a file based on a condition.

String str;
double one = 0.00;
double two = 0.00;
BufferedReader in = new BufferedReader(new FileReader(myFile));

while((str = in.readLine()) != null){
     if(str.charAt(21) == '1'){
         one += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51));
     }

     else{
         two += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51));
     }
   }

in.close();
System.out.println("One: " + one);
System.out.println("Two: " + two);      

The output is like:

One: 2773554.02
Two: 6.302505836000001E7

Question:

None of the input have more then two decimals in them. The way one and two are getting calculated exactly same.

Then why the output format is like this.

What I am expecting is:

One: 2773554.02
Two: 63025058.36

Why the printing is in two different formats ? I want to write the outputs again to a file and thus there must be only two digits after decimal.

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
Vicky
  • 16,679
  • 54
  • 139
  • 232
  • 6
    Use `DecimalFormat` - eg http://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java – scibuff Mar 22 '12 at 11:28
  • 3
    Also, I'd use `BigDecimal` instead of `double` to avoid rounding errors introduced by parsing doubles (this is why you see 00000001 at the end of the second number) – beny23 Mar 22 '12 at 11:31
  • As always : http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html - A very worthwhile read. – mcfinnigan Mar 22 '12 at 11:42

1 Answers1

1

The issue with the missing accuracy is caused by using double. Use BigDecimal to avoid this.

For printing, use DecimalFormat like this:

DecimalFormat format = new DecimalFormat("0.##");
System.out.println("One: " + format.format(one));
System.out.println("Two: " + format.format(two));

Documentation for DecimalFormat: http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

nwinkler
  • 52,665
  • 21
  • 154
  • 168