0

I have read many posts on Math.round and DecimalFormat etc. However I dont know how id go about correctly using either of the above within code where its more complicated than just simply declared variables.

 List<Float> depthCopy = new ArrayList<>(depthAdd);

        ...//collection sort
        ...//iterate i over arraylist

      if (depthCopy.get(i).equals(depthAdd.get(depthAdd.size() - 1))) {
          System.out.println("Wettest year: " + (1000 + i) + " "
                  + //FORMAT HERE?(depthAdd.get(depthAdd.size() - 1)));
            }
        }  

This returns a value of: Wettest year: 2002 1146.3999

1146.3999 is correct

however I need to print this value formatted/rounded to 1 decimal place i.e: 1146.4

I have tried the following:

System.out.println("Wettest year: " + (1930 + i) + " "
                    + (double)Math.round(depthAdd.get(depthAdd.size() - 1)));

It returns 1146.0 (incorrect)

Printed value im looking to get is 1146.4. What is the best way to achieve this? Why would this way be better than other alternatives?

SOLUTION: Instead of Math.round use DecimalFormat

DecimalFormat df = new DecimalFormat("####.#");
              System.out.println("Wettest year: " + (1000 + i) + " "
                      + df.format((depthAdd.get(depthAdd.size() - 1)));

Abbie
  • 153
  • 1
  • 3
  • 13
  • Duplicate? I have explained why this is not a duplicate. There are many threads on simple variables: `double num = 540.512` `double sum = 1978.8` where you would so something like the following to resolve: `double total = (double) Math.round((num / sum * 100) * 10) / 10;` OR `double total = Math.round((num / sum * 100) * 10) / 10.0;` – Abbie Aug 24 '15 at 14:49
  • Did you try 'Math.round(f * 10.0f) / 10.0f)' (where 'f' is your float)? – Dimitar Aug 24 '15 at 14:51
  • how could I use that though^ given this: `(depthAdd.get(depthAdd.size() - 1)));` is what gives me my value in the first place? – Abbie Aug 24 '15 at 14:55
  • Look at DecimalFormat – FredK Aug 24 '15 at 15:07
  • @Abbie: (depthAdd.get(depthAdd.size() - 1))) gives you the float, right? Assign it to a local variable and use that reference in the calculation. Or am I missing something? – Dimitar Aug 25 '15 at 11:56

0 Answers0