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 210 views
2 answers 280 views
3 answers 298 views
1 answer 160 views
2 answers 253 views
1 answer 266 views
...