Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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 121 views
2 answers 178 views
3 answers 153 views
1 answer 154 views
3 answers 292 views
3 answers 271 views
...