Wednesday, January 29, 2014

How to round a number to n'th decimal places in java?

Source:
public class RoundNumber {
   public static void main(String[] args) {
      System.out.println(round(1.23456789));
      System.out.println(round(9.99999999));
      System.out.println(round(2.22222222));
      System.out.println(round(3.123451234512345));
      System.out.println(round(9.87654321));
   }
 
   public static double round(double number) {\
      // round to five places
      return (double)Math.round(number * 100000) / 100000;
   }
}

Output:
   $ java RoundNumber 
   1.23457
   10.0
   2.22222
   3.12345
   9.87654

Blog Archive