How to round an array of float numbers to N specified decimal places in Java

1 Answer

0 votes
import java.text.DecimalFormat;
import java.math.RoundingMode;
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
	    DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);
        
        for (Number num : Arrays.asList(378.538721, 17, 0.23, 0.89473, 84930.2311524)) {
            Double d = num.doubleValue();
            System.out.println(df.format(d));
        }
    }
}




/*
run:

378.539
17
0.23
0.895
84930.232

*/

 



answered Aug 9, 2021 by avibootz

Related questions

2 answers 199 views
2 answers 266 views
3 answers 291 views
1 answer 158 views
2 answers 243 views
1 answer 257 views
...