51

I am new to programming so I apologize beforehand. I am running a program and am having a problem with the System.out.printf method in Java. I know everything else in the program is working correctly (tested it). However this does not seem to work.

The error is:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Advisor_Score.main(Advisor_Score.java:17)

My code is:

import java.lang.Math;
public class Advisor_Score {
    public static void main(String[] args){ 
        double l[] = {101,1,1,1};
        double k[] = {102,2,2,4};
        double m[] = {103,5,5,5,5,5,5,5};
        double All_users[][]={l,k,m};
        double sum[]=new double [All_users.length];
        double [] raw_advisor=new double [All_users.length];
        double []advisor_score= new double [All_users.length];
        for (int i=0;i<All_users.length;i++){
                for(int j=1;j<All_users[i].length;j++){
                        sum[i]+=All_users[i][j];
                }
                raw_advisor[i]=((sum[i]-(3*(All_users[i].length-1)))/4);
                advisor_score[i]= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor[i])));
                System.out.printf("%d: %d\n", All_users[i][0], advisor_score[i]);
                }       
    }
}

Not really sure why it's not working.

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
Spencer
  • 21,348
  • 34
  • 85
  • 121

2 Answers2

147

%d represents an integer; you want to use %f for a double. See the formatting string syntax in the Javadoc

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 24
    It's quite inconvenient that `%d` is not for a double... `double` starts with the letter `d` after all! :D – hyper-neutrino Aug 29 '15 at 02:09
  • 3
    @JamesSmith I suppose; it stands for [decimal](http://stackoverflow.com/q/13409014/309308), as opposed to `%x` for hexadecimal or `%o` for octal. C will also let you use `%i` as an "integer" synonym for `%d`, but it looks like Java doesn't – Michael Mrozek Aug 29 '15 at 15:20
  • If you used `%d` format to only display the integer value of your Double, you must also convert your Double value to an integer value: `Double value = new Double(102.0); String toDisplay = String.format("%d", value.intValue());` – Alexandre Nov 16 '18 at 15:19
  • How do we truncate to decimal places? – IgorGanapolsky Jan 20 '20 at 17:55
0

if your dataType is bigDecimal then have to use : %g

Amer Alzibak
  • 1,489
  • 15
  • 16