-1
public class Exercise05_08 {
  public static void main(String[] args) {
    System.out.println("Celsius\t\tFahrenheit\t|\tFahrenheit\tCelsius");
    System.out.println("---------------------------------------------");

    double celsius = 40; double farenheit = 120;
    for (int i = 1; i <= 10; celsius--, farenheit -= 10, i++) {
      System.out.println(celsius + "\t\t" + celsiusToFahrenheit(celsius) + "\t|\t" +     farenheit + "\t\t" + fahrenheitToCelsius(farenheit));
    }
  }

  public static double celsiusToFahrenheit(double celsius) {
    return (9.0 / 5.0) * celsius + 32;
  }

  public static double fahrenheitToCelsius(double fahrenheit) {
    return (5.0 / 9) * (fahrenheit - 32);
  }
}

Some of the values print out with several decimal places and i want all of the values to print with just 2 decimal places.

4 Answers4

3

You can have 2 decimal places using DecimalFormat:

DecimalFormat myFormatter = new DecimalFormat("#.00");
String output = myFormatter.format(value);

You can find additional information about custom formats and patterns construction (and how to use them) here.

alex
  • 10,900
  • 15
  • 70
  • 100
0

You should use the format() method:

System.out.format("%.2f", celsius); 

will format the value with 2 decimal places.

Since you are using println() you may want to include "\n" in the end of your format strings to insert a newline.

user207421
  • 305,947
  • 44
  • 307
  • 483
mscoon
  • 88
  • 6
0

Make the following change to not print only 2 digits after dot:

NumberFormat formatter = new DecimalFormat("%.2f");
String s = formatter.format(celsiusToFahrenheit(celsius));

And print:

System.out.println(celsius + "\t\t" + s + "\t|\t" + farenheit + "\t\t" + fahrenheitToCelsius(farenheit));
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
-1

Easy fix would be to multiply the outcome by 100, cast them to an int, then divide them by 100 again to a double.

It might not be the most elegant solution, but it would work..

EDIT: apparently there's a more elegant solution, so forget it.

Lonefish
  • 647
  • 2
  • 11
  • 32
  • No it doesn't. See [here](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java/12684082#12684082) for proof. – user207421 Feb 03 '14 at 23:44