Author Topic: Illegal Format Conversion Exception  (Read 3788 times)

0 Members and 1 Guest are viewing this topic.

Offline Super_mario666

  • Knight
  • **
  • Posts: 160
  • Cookies: 7
  • Professional Badass
    • View Profile
Illegal Format Conversion Exception
« on: March 15, 2013, 07:34:18 pm »
im having a problem while try to output data to a file. it keeps throwing "java.util.IllegalFormatConversionException"


this the part with the problem


Code: (java) [Select]
           try{

            out = new Formatter("allaccounts.txt");
            }
            catch(FileNotFoundException ex){
                System.err.println("Error: File not Found!");
                System.exit(1);
                return;
            }



            for(int i = 0; i < start.getnumAcc();i++)
      {
         
         outs.format("%d ",users[i].getNum());   
         outs.format("%s ",users[i].getName());
         outs.format("%s ",users[i].getPass());   
         outs.format("%d\n",users[i].getBalan()); //returns double- line that throws the exception
      }


      outs.close();




when i googled it i found out it  the %d should be a %f. but when i do that the data gets written all wrong.

for example, if users.getBalan() returns 123.45 it would be instead write 123.450000 to it.

« Last Edit: March 15, 2013, 07:34:45 pm by Super_mario666 »
The Bigger they are...The more likely you'll get your ass kicked

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: Illegal Format Conversion Exception
« Reply #1 on: March 15, 2013, 08:51:54 pm »
You can't cast a float to an int. So output a float, and you can control how many numbers should be after the dot by doing:
%.Nf
Where N is a number, example: %.2f, would give you 123.45

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Illegal Format Conversion Exception
« Reply #2 on: March 15, 2013, 09:04:56 pm »
This should answer your questions: (from http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

Quote
'd' integral The result is formatted as a decimal integer

Quote
Integral - may be applied to Java integral types: byte, Byte, short, Short, int and Integer, long, Long, and BigInteger


Quote
The number of digits in the result for the fractional part of m or a is equal to the precision.  If the precision is not specified then the default value is 6. If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm.  Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value,use Float.toString(float) or Double.toString(double) as appropriate.