EN
Java - round ArrayList elements to two decimal places
0 points
In this article, we would like to show you how to round ArrayList elements to two decimal places in Java.
Quick solution:
xxxxxxxxxx
1
for (int i = 0; i < myArrayList.size(); i++) {
2
double newValue = (double) Math.round(myArrayList.get(i) * 100d) / 100d;
3
myArrayList.set(i, newValue);
4
}
or
xxxxxxxxxx
1
for (Double item : myArrayList) {
2
double newValue = (double) Math.round(item * 100d) / 100d;
3
myArrayList.set(myArrayList.indexOf(item), newValue);
4
}
In this example, we loop through the numbers
ArrayList using for loop and round each element using Math.round()
method.
xxxxxxxxxx
1
package arraylistOperations;
2
3
import java.util.*;
4
5
public class Example {
6
7
public static void main(String[] args) {
8
List<Double> numbers = new ArrayList<>() {{
9
add(1.123456);
10
add(2.123456);
11
add(3.123456);
12
}};
13
14
for (int i = 0; i < numbers.size(); i++) {
15
double newValue = (double) Math.round(numbers.get(i) * 100d) / 100d;
16
numbers.set(i, newValue);
17
}
18
19
System.out.println(numbers); // [1.12, 2.12, 3.12]
20
}
21
}
Output:
xxxxxxxxxx
1
[1.12, 2.12, 3.12]
In this example, we loop through the numbers
ArrayList using for-each loop and round each element using Math.round()
method.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<Double> numbers = new ArrayList<>() {{
7
add(1.123456);
8
add(2.123456);
9
add(3.123456);
10
}};
11
12
for (Double number : numbers) {
13
double newValue = (double) Math.round(number * 100d) / 100d;
14
numbers.set(numbers.indexOf(number), newValue);
15
}
16
17
System.out.println(numbers); // [1.12, 2.12, 3.12]
18
}
19
}
Output:
xxxxxxxxxx
1
[1.12, 2.12, 3.12]