Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.text.DecimalFormat;
- import java.util.Scanner;
- class RoundTest {
- /**
- * Program: RoundTest.java
- * Purpose: Compare unformatted, formatted and rounded numbers
- * Creator: Chris Clarke
- * Created: 29.05.2014
- * Note: Using DecimalFormat, it only goes up to 1.9, NOT 2.0!! So beware!!
- */
- public static void main(String []args) {
- DecimalFormat df = new DecimalFormat("0.0");
- Scanner in = new Scanner(System.in);
- String s = "";
- double a;
- for (int i=0; i<3; i++) {
- System.out.println("Press enter to continue...");
- s = in.nextLine();
- System.out.printf("Test %d%n", (i+1));
- switch (i) {
- case 0: System.out.println( "Without formatting:");
- for (a=0.0; a<=2.0; a+=0.1) {
- System.out.println(a);
- } // end for a
- break;
- case 1: System.out.println( "Using DecimalFormat:");
- for (a=0.0; a<=2.0; a+=0.1) {
- System.out.println( df.format(a));
- } // end for
- break;
- case 2: // the best way to display numbers
- System.out.println( "Using round() method:");
- for (a=0.0; a<=2.0; a+=0.1) {
- // round to 1 decimal place
- a = round(a, 1);
- System.out.println(a);
- } // end for
- break;
- } // end switch
- } // end for i
- } // end main()
- // round d to p decimal places
- public static double round(double d, int p) {
- double n = Math.pow(10, p); // 10 ^ p
- d *= n;
- d = Math.round(d); // round to nearest int
- d /= n;
- return d;
- } // end function round()
- } // end class RoundTest
Advertisement
Add Comment
Please, Sign In to add comment