0

I'm trying to figure out how to round numbers at the moment.

   public static void main (String [] args) {
      double outsideTemperature;

      outsideTemperature = 103.46432;

      /* Your solution goes here  */
      System.out.printf("%3.6s\n", outsideTemperature);

   }
}

This code yields a printout of 103.46 which is great, except that the next test that is run has a variable of 70.116 and is expecting an output of 70.12.

How do I get the answer to round up and pass both tests?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Frost813
  • 21
  • 1
  • 5
  • why are you not using `Math.round()`? –  Jun 09 '20 at 02:35
  • Because I haven't been taught that yet. I'm 6 weeks in to learning Java. This is all pretty new to me. – Frost813 Jun 09 '20 at 02:38
  • Does this answer your question? [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) – HC Tang Jun 09 '20 at 02:41
  • I'm still getting the same issue as the previous code: Testing outsideTemperature = 70.1164 Output differs. See highlights below. Your output 70.116 Expected output 70.12 – Frost813 Jun 09 '20 at 02:45

2 Answers2

2

Your first stop when you have such a question, should be the documentation.

System.out.printf points to Format String Syntax.

To format floating point numbers, you need %f, not %s (which formats strings but doesn't know about numbers specifically):

System.out.printf("%.2f\n", outsideTemperature);

Before the dot is the total width of the field (which you're not interested in), and behind the dot is the number of places behind the decimal point (2 in your case)

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • Thank you! I've been bouncing all around trying to figure out exactly what I should use. I completely overlooked %f. I've been so focused on %s and %d. – Frost813 Jun 09 '20 at 02:54
  • 1
    Very much true explanation, besides that you are free to use DecimalFormat which does lots of work done for you. DecimalFormat df = new DecimalFormat("###.##"); System.out.println(df.format(outsideTemperature)); – Vivek Swansi Jun 09 '20 at 02:58
1

You can use Math.round():

outsideTemp = 103.46432;

How it works:

Math.round(103.46432 * 100) = 10346.00 (rounded to nearest value)

Math.round(103.46432 * 100) / 100 = 103.46

roundedDouble = Math.round(outsideTemp * 100.0) / 100.0;
System.out.println(roundedDouble);
Community
  • 1
  • 1
HC Tang
  • 31
  • 10
  • Thank you for the help. While this didn't work for this particular application, I'll keep this in my notes for future use. – Frost813 Jun 09 '20 at 02:56