Languages
[Edit]
EN

Java - round ArrayList elements to two decimal places

0 points
Created by:
Payne
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<>() {{
            add(1.123456);
            add(2.123456);
            add(3.123456);
        }};

        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<>() {{
            add(1.123456);
            add(2.123456);
            add(3.123456);
        }};

        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

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join