Results 1 to 4 of 4
- 02-26-2011, 10:18 PM #1
Member
- Join Date
- Nov 2010
- Posts
- 38
- Rep Power
- 0
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"));
- 02-26-2011, 10:34 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,546
- Rep Power
- 11
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.
- 02-26-2011, 11:13 PM #3
Member
- Join Date
- Nov 2010
- Posts
- 38
- Rep Power
- 0
It works! Thanks.
- 02-27-2011, 12:03 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,546
- Rep Power
- 11
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
-
couldnt find the answer..
By amaliutz in forum New To JavaReplies: 12Last Post: 02-03-2011, 04:08 PM -
String formatting
By sunde887 in forum New To JavaReplies: 5Last Post: 01-23-2011, 11:24 AM -
String and number formatting
By computerbum in forum New To JavaReplies: 1Last Post: 04-27-2010, 05:06 PM -
Formatting String
By ersachinjain in forum Advanced JavaReplies: 13Last Post: 10-21-2009, 09:26 PM -
formatting String
By bugger in forum New To JavaReplies: 1Last Post: 11-16-2007, 07:27 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks