Showing posts with label round. Show all posts
Showing posts with label round. Show all posts

Round doubles to the nth decimal

Question:
How can you round doubles to the nth decimal?

Answer:
For 5 digits precision:
   (double)Math.round(value * 100000) / 100000
The number of zeros indicate the number of decimals.

Code:
public class Rounding {
   public static void main(String[] args) {
 
      double pi = 3.14159265359;
      System.out.println(pi);
 
      System.out.println( Math.round(pi) );
      System.out.println( (double)Math.round(pi*10)/10 );
      System.out.println( (double)Math.round(pi*100)/100 );
      System.out.println( (double)Math.round(pi*1000)/1000 );
      System.out.println( (double)Math.round(pi*10000)/10000 );
      System.out.println( (double)Math.round(pi*100000)/100000 );
      System.out.println( (double)Math.round(pi*1000000)/1000000 );
      System.out.println( (double)Math.round(pi*10000000)/10000000 );
 
   }
}

Output:
$ java Rounding 
3.14159265359
3
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927

How can you round doubles to the nth decimal?

Question:
How can you round doubles to the nth decimal?

Answer:
Using the Math.round method and formating with the DecimalFormat class.

Code:
import java.text.DecimalFormat;
 
public class RoundDoubles {
   public static void main(String[] args) {
 
      double d1 = 0;
      double d2 = 1.49999;
      double d3 = 3.14159265359;
      double d4 = 98.5555555;
 
      //the number of zeros indicate the number of decimals.
      d1 = (double)Math.round(d1 * 100) / 100;
      d2 = (double)Math.round(d2 * 100) / 100;
      d3 = (double)Math.round(d3 * 100) / 100;
      d4 = (double)Math.round(d4 * 100) / 100;
 
      //the number of .0's indicate right padding.
      DecimalFormat df = new DecimalFormat("0.00"); 
      System.out.println(df.format(d1));
      System.out.println(df.format(d2));
      System.out.println(df.format(d3));
      System.out.println(df.format(d4));
   }
}

Output:
$ java RoundDoubles
0.00
1.50
3.14
98.56