Jeremy Eisner
Jeremy Eisner

Reputation: 51

Rounding int to 1 decimal place?

So in the following set of code I don't understand why "%.1f" will not round y to 1 decimal, I get the following when running the program:

123 F = Exception in thread "main" 
    java.util.IllegalFormatConversionException: f != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
    at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708)
    at java.util.Formatter.format(Formatter.java:2488)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at Check03A.main(Check03A.java:17)

I also tried Math.round(y * 10) / 10 but it gives me for example 29.0 instead of 28.9

import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;

public class Check03A

{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        PrintStream print = new PrintStream(System.out);
        print.println("Enter the temperature in Fahrenheit");
        int x = scan.nextInt();
        int y = 5 * (x - 32) / 9;
        print.printf(x + " F = " + "%.1f", y + " C");
    }
}

Upvotes: 0

Views: 269

Answers (3)

fge
fge

Reputation: 121702

The problem is here:

print.printf(x + " F = " + "%.1f", y + " C");

There are two arguments to this method:

  • x + " F = " + "%.1f" (the format string),
  • y + "C" (the argument)

Condensing the first argument, the statement becomes:

print.printf(x + "F = %.1f", y + "C");

The problem: y + "C". Why? Well, one argument of the + operator is a String; therefore, this + becomes a string concatenation operator and what the argument will ultimately be is String.valueOf(y) + "C".

But the format specification in the format string is%.1f, which expects a float or double, or their boxed equivalents. It does not know how to handle a String argument.

Hence the error.


There is also the problem that you are doing an integer division, but this is not the topic of this question. Provided that all numeric problems are solved, your printing statement will ultimately be:

print.printf("%.1f F = %.1f C", x, y);

Upvotes: 2

Deepu--Java
Deepu--Java

Reputation: 3820

Make y as float if you want to use %f

float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y ).print("C");

Upvotes: 0

sunysen
sunysen

Reputation: 2351

public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        PrintStream print = new PrintStream(System.out);
        print.println("Enter the temperature in Fahrenheit");
        int x = scan.nextInt();
        //change it
        float y = 5 * (x - 32) / 9;
        print.printf(x + " F = " + "%.1f", y).print(" C");
    }

Upvotes: 0

Related Questions