1

I am a completely new to programming and am running through a tutorial exercise that is prompting me to do the following:

Prompt a user to enter her height in inches. If she is less than 54 inches tall, notify her that she cannot ride the Raptor and how many more inches she needs. If she is at least 54 inches tall, notify her that she can ride the Raptor.

The code I currently have written for this prompt is as follows

    import java.util.Scanner;
public class Main {
 public static void main(String [] args) {
  Scanner scnr = new Scanner(System.in);
   double userHeight = 0.0;
   double heightDiff = 0.0;

   System.out.println("Enter your height in inches: ");
      userHeight = scnr.nextDouble();
      heightDiff = 54 - userHeight;

      if (userHeight >= 54.0) {
         System.out.println(userHeight);
         System.out.println("Great, you can ride the Raptor!");
      }
      else {
         System.out.println(userHeight);
         System.out.println("Sorry, you cannot ride the Raptor. You need " + heightDiff + " more inches.");
      }

      return; 
 }
}

When I run the program it works great except when I use inputs that involve decimals, such as 52.3 inches for example, my output for heightDiff is a long decimal because of the float number.

This is the output with an input of 52.3:

Enter your height in inches: 52.3 Sorry, you cannot ride the Raptor. You need 1.7000000000000028 more inches.

How can I get my "...1.7000000000000028 more inches." output to be a decimal value rounded to one decimal and be 1.7? I need it to work for any input value with a decimal (for example 51.5 outputs "2.5 more inches." etc.)?

A.J. Uppal
  • 17,608
  • 6
  • 40
  • 70
  • 2
    Possible duplicate of [How to round a number to n decimal places in Java](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – P.J.Meisch May 24 '17 at 03:06

1 Answers1

2

You can use String.format("%.2f", heightDiff) like this:

System.out.println("Sorry, you cannot ride the Raptor. You need " + String.format("%.2f", heightDiff )+ " more inches.");

String.format(..) will not change heightDiff. If you try to print it again, heightDiff will still print out as 1.7000000000000028. String.format(..) will only format the value of heightDiff only for the time when you are printing heightDiff (via System.out.println(..)). That is it.

To understand more about String.format(..), google it and you will find plenty of explanations. You can also find out what else can be achieved with String.format(..).

Faraz
  • 4,939
  • 3
  • 18
  • 57