Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - round ArrayList elements to two decimal places

0 points
Created by:
654

In this article, we would like to show you how to round ArrayList elements to two decimal places in Java.

Quick solution:

``````for (int i = 0; i < myArrayList.size(); i++) {
double newValue = (double) Math.round(myArrayList.get(i) * 100d) / 100d;
myArrayList.set(i, newValue);
}``````

or

``````for (Double item : myArrayList) {
double newValue = (double) Math.round(item * 100d) / 100d;
myArrayList.set(myArrayList.indexOf(item), newValue);
}``````

## Practical examples

### Example 1

In this example, we loop through the `numbers` ArrayList using for loop and round each element using `Math.round()` method.

``````package arraylistOperations;

import java.util.*;

public class Example {

public static void main(String[] args) {
List<Double> numbers = new ArrayList<>() {{
}};

for (int i = 0; i < numbers.size(); i++) {
double newValue = (double) Math.round(numbers.get(i) * 100d) / 100d;
numbers.set(i, newValue);
}

System.out.println(numbers);  // [1.12, 2.12, 3.12]
}
}``````

Output:

``[1.12, 2.12, 3.12]``

### Example 2

In this example, we loop through the `numbers` ArrayList using for-each loop and round each element using `Math.round()` method.

``````import java.util.*;

public class Example {

public static void main(String[] args) {
List<Double> numbers = new ArrayList<>() {{
}};

for (Double number : numbers) {
double newValue = (double) Math.round(number * 100d) / 100d;
numbers.set(numbers.indexOf(number), newValue);
}

System.out.println(numbers);  // [1.12, 2.12, 3.12]
}
}``````

Output:

``[1.12, 2.12, 3.12]``

## Related posts

Join to our subscribers to be up to date with content, news and offers.