1

I am trying to produce right aligned numbers looking a bit like this:

  12345
   2345

but I clearly does not understand the syntax. I have been trying to follow these instructions. and Come up with the following attempt (it is integers so d and I want width 7 and 0 decimals):

public class test {

    public static void main( String[] args ) {
        System.out.format("%7.0d%n", 12345);
        System.out.format("%7.0d%n",  2345);
    }
}

but no matter what I do I seem to end up with IllegalFormatPrecisionException. Is there a way to do this using this tool? If not how else would you do it?

1
  • The .0 is for floating point. You don't need it. Commented Nov 21, 2011 at 16:49

4 Answers 4

3

You can do something like this:

public class Test {
    public static void main( String[] args ) {
        System.out.format("%7d%n", 12345);
        System.out.format("%7d%n",  2345);
    }
}

Essentially this code asks Java to pad the string with spaces so that the output is exactly 7 characters.

Sign up to request clarification or add additional context in comments.

1 Comment

+1: You don't need the space. I would use %n instead of \n
1

Do it like this:

public class test {

    public static void main( String[] args ) {
        System.out.format("%7d%n", 12345);
        System.out.format("%7d%n",  2345);
    }
}

Comments

1

From the linked page, it shows this:

System.out.format("%,8d%n", n); // --> " 461,012"

You can omit the comma, and change the 8 to a 7

Comments

0

converter %d is for integers and %f is for float. "%7.0d%n" is used with a float(i.e., as %7.0f%n) and "%7d%n" is used for integer representation.this is the reason for IllegalFormatPrecisionException exception.

Reference link http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.