0
    double energy, mass;
    double speedOfLight = 299792458.0;
    // Get mass
    System.out.print("Mass? ");
    mass = keyboard.nextDouble();
    // Calculate energy
    energy = mass*Math.pow(speedOfLight, 2);
    // Round to 1 decimal place
    energy = Math.round(energy * 10.0) / 10.0;
    System.out.printf("The energy is " +energy+ " Joules");
    // Close scanner
    keyboard.close();

It is returning, "The energy is 8.987551787368176E16 Joules" when it should be returning, "The energy is 89875517873681760.0 Joules"

1 Answers1

4

Math.round is working as intended, returning the nearest integer (but the output is in scientific notation). The problem is in the printing of the number. You can use printf's format specifiers to print the number in the format you want:

System.out.printf("The energy is %.1f Joules", energy);
Leon
  • 2,926
  • 1
  • 25
  • 34
  • Thanks for the help, unfortunately when trying your method I am given the error message, "Mass? 1 The energy is Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source) at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source) at java.util.Formatter$FormatSpecifier.print(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.io.PrintStream.format(Unknown Source) at java.io.PrintStream.printf(Unknown Source) at P2.main(P2.java:42)" – Robin Luke Aug 23 '18 at 21:11
  • Yes, I used the wrong format specifier (`d` is for long/integer, `f` is for float/double). I corrected the snippet. – Leon Aug 23 '18 at 21:14
  • Ah, thank you for that, but it still outputs, "The energy is 89875517873681760.000000 Joules" Is it possible to cut it off after the first 0? – Robin Luke Aug 23 '18 at 23:04
  • I added a `.1` to the format specifier, which causes Java to print 1 decimal place. Similarly, you could use `.5`, if you want 5 decimal places. – Leon Aug 24 '18 at 07:40