Skip to content
Advertisement

What is the right printf syntax when formatting a double? [closed]

I’m stuck at the printf statement. Can anyone tell, what’s the right syntax for printf when formatting a double?

public static void main(String[] args){
    System.out.printf("%-15s %-5s" + " | " + "%5s %15s n", "Celcius", "Fahrenheit", "Fahrenheit", "Celcius");
    for(double celcius = 40, fahrenheit = 120; celcius >= 31 && fahrenheit >= 30; celcius--, fahrenheit--){
    System.out.printf("%.1-15f%.1-5f|%.115f%.115fn", celcius, celciusToFahrenheit(celcius), fahrenheit, fahrenheitToCelcius(fahrenheit));
    }
}

public static double celciusToFahrenheit(double celcius){
    double fahrenheit = (9.0 / 5) * (celcius + 32); 
    return fahrenheit;        
}

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

Advertisement

Answer

These are the System.out.printf() format rules:

%[flags][width][.precision]conversion-character

You can find plenty of examples and explanation of printf() here and here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement