Results 1 to 4 of 4
  1. #1
    rippon is offline Member
    Join Date
    Nov 2010
    Posts
    38
    Rep Power
    0

    Default trivial string formatting problem that I just cannot find the answer to

    Despite all my searching on the web and in books, I cannot find the solution to this trivial problem.

    All I want to do is output (in a JTextField called 'messageBox') the value of PI to two decimal places in a text field of total length five characters.

    I think I need to do some 'wrapping' and then some string formatting, and I +think+ I need to give the format method a formatting string. Hope the intent of the following attempted code is clear, and hope you can help. Thanks in advance.

    Java Code:
                double myPI = 3.1415926535;
                Double myWrappedPI = 0.0;
    
                myWrappedPI = myPI;
                messageBox.setText("myWrappedPI approximated is: " + 
                                  myWrappedPI.toString().format("%5.2d"));

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    You might find the format() method of String easier to deal with

    Java Code:
    String.format("%5.2f", myPI);
    String.format("%5.2f", myWrappedPI);

    Note d is for decimal (a way of representing ints), f is for floatingpoint.

  3. #3
    rippon is offline Member
    Join Date
    Nov 2010
    Posts
    38
    Rep Power
    0

    Default

    It works! Thanks.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    You're welcome.

    For future reference the format string syntax is described (and somewhat illustrated) in the Formatter API docs: there is too much there to absorb in a single session, but I find it's a handy place to go back to when I want something formatted (date, hex value etc).

Similar Threads

  1. couldnt find the answer..
    By amaliutz in forum New To Java
    Replies: 12
    Last Post: 02-03-2011, 04:08 PM
  2. String formatting
    By sunde887 in forum New To Java
    Replies: 5
    Last Post: 01-23-2011, 11:24 AM
  3. String and number formatting
    By computerbum in forum New To Java
    Replies: 1
    Last Post: 04-27-2010, 05:06 PM
  4. Formatting String
    By ersachinjain in forum Advanced Java
    Replies: 13
    Last Post: 10-21-2009, 09:26 PM
  5. formatting String
    By bugger in forum New To Java
    Replies: 1
    Last Post: 11-16-2007, 07:27 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •