brilliant_moves

RoundTest.java

May 29th, 2014
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.51 KB | None | 0 0
  1. import java.text.DecimalFormat;
  2. import java.util.Scanner;
  3.  
  4. class RoundTest {
  5.  
  6.     /**
  7.     *   Program:    RoundTest.java
  8.     *   Purpose:    Compare unformatted, formatted and rounded numbers
  9.     *   Creator:    Chris Clarke
  10.     *   Created:    29.05.2014
  11.     *   Note:       Using DecimalFormat, it only goes up to 1.9, NOT 2.0!! So beware!!
  12.     */
  13.  
  14.     public static void main(String []args) {
  15.  
  16.         DecimalFormat df = new DecimalFormat("0.0");
  17.         Scanner in = new Scanner(System.in);
  18.         String s = "";
  19.         double a;
  20.  
  21.         for (int i=0; i<3; i++) {
  22.             System.out.println("Press enter to continue...");
  23.             s = in.nextLine();
  24.  
  25.             System.out.printf("Test %d%n", (i+1));
  26.             switch (i) {
  27.                 case 0: System.out.println( "Without formatting:");
  28.                     for (a=0.0; a<=2.0; a+=0.1) {
  29.                         System.out.println(a);
  30.                     } // end for a
  31.                     break;
  32.                 case 1: System.out.println( "Using DecimalFormat:");
  33.                     for (a=0.0; a<=2.0; a+=0.1) {
  34.                         System.out.println( df.format(a));
  35.                     } // end for
  36.                     break;
  37.                 case 2: // the best way to display numbers
  38.                     System.out.println( "Using round() method:");
  39.                     for (a=0.0; a<=2.0; a+=0.1) {
  40.                         // round to 1 decimal place
  41.                         a = round(a, 1);
  42.                         System.out.println(a);
  43.                     } // end for
  44.                     break;
  45.             } // end switch
  46.         } // end for i
  47.     } // end main()
  48.  
  49.     // round d to p decimal places
  50.     public static double round(double d, int p) {
  51.         double n = Math.pow(10, p); // 10 ^ p
  52.         d *= n;
  53.         d = Math.round(d); // round to nearest int
  54.         d /= n;
  55.         return d;
  56.     } // end function round()
  57.  
  58. } // end class RoundTest
Advertisement
Add Comment
Please, Sign In to add comment