How to round a double to N decimal places in Java

2 Answers

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

public class MyClass {
    public static void main(String args[]) {
        DecimalFormat df = new DecimalFormat("#.###"); // can be changed to: #.##, #.####
        df.setRoundingMode(RoundingMode.CEILING);

        for (Number n : Arrays.asList(15, 751.123456, 0.87241, 98371.0984877, 0.01343, 0.2)) {
            Double d = n.doubleValue();
            System.out.println(df.format(d));
        }
    }
}



/*
run:

15
751.124
0.873
98371.099
0.014
0.2

*/

 



answered Sep 4, 2019 by avibootz
0 votes
import java.util.Arrays;
import java.math.*;

public class MyClass {
    public static void main(String args[]) {

        for (Number n : Arrays.asList(15, 751.123456, 0.87241, 98371.0984877, 0.01343, 0.2)) {
            Double d = n.doubleValue();
            System.out.println(BigDecimal.valueOf(d).setScale(3, BigDecimal.ROUND_HALF_UP));
        }
    }
}



/*
run:

15.000
751.123
0.872
98371.098
0.013
0.200

*/

 



answered Sep 4, 2019 by avibootz

Related questions

1 answer 132 views
2 answers 190 views
3 answers 195 views
1 answer 164 views
3 answers 314 views
3 answers 285 views
...