-2

I am posting my code. I do not want my answer round up. Example: In the second column for feet it should be 65.574, not 65.580.

public class Exercise_06_09 {

    public static void main(String[] args) {

        System.out.printf("%-15s%-15s|    %-15s%-15s\n","Feet","Meters","Meters","Feet");
        System.out.println( String.format("%62s"," ").replace(' ', '-'));

        for (double m = 20, f = 1  ; f <=10; f++, m+=5) {           
            System.out.printf("%-15.1f%-15.3f|    %-15.1f%-15.3f\n", f, footToMeter(f), m, meterToFoot(m));
        }        
    }

    //Convert from meter to foot
    public static double meterToFoot(double meter) {
        return 3.279 * meter;
    }

    //Convert from foot to meter
    public static double footToMeter(double foot) {
        return  0.305 * foot;
    }    
}

This is the output I get

Feet Meters | Meters Feet

1.0 0.305 | 20.0 65.580
2.0 0.610 | 25.0 81.975
3.0 0.915 | 30.0 98.370
4.0 1.220 | 35.0 114.765
5.0 1.525 | 40.0 131.160
6.0 1.830 | 45.0 147.555
7.0 2.135 | 50.0 163.950
8.0 2.440 | 55.0 180.345
9.0 2.745 | 60.0 196.740
10.0 3.050 | 65.0 213.135

CodeZero
  • 1,649
  • 11
  • 18
  • 6
    It's not an *output* problem. The value your `meterToFoot` function is calculating **is** 65.58, not 65.574. Because 20 x 3.279 is 65.58 (just work it out: 20 x 3.279 is 2 x 10 x 3.279 which is 2 x 32.79 which if we do the whole and fractional parts separately is 2 x 32 + 2 x 0.79, which is 64 + 1.58, which is 65.58). – T.J. Crowder Feb 04 '18 at 17:18
  • You might want to check your math on `3.279 * 20` again – OneCricketeer Feb 04 '18 at 17:20
  • Yes, when I do the math it is 65.58, but the example in the book shows my outcome should be 65.574? – hhayes29 Feb 04 '18 at 17:57
  • So they have a more precise factor? – user unknown Feb 04 '18 at 18:17

2 Answers2

1

You can use BigDecimal class if you don't want to round off to a number.

Use something like:

BigDecimal bigDecimal = new BigDecimal(3.279 * meter);

You would get the following output: 65.5799999999999982946974341757595539093017578125

Now convert the value to String and get the substring where the end index is 3 decimal places after decimal point.

Rohith Joseph
  • 603
  • 1
  • 5
  • 17
0

You could multiple by 10^n ( n being the amount of digits to keep ) and then get rid of the decimals. Maybe cast it as an int. Then divide it by 10^n again.

Carson Graham
  • 519
  • 4
  • 15