• Post Reply Bookmark Topic Watch Topic
  • New Topic

Format number string to include leading zeros  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to take the input of several JTextField's that contain integers and concatenate them into a formatted String (for both display and to be saved). I'm having trouble getting leading zeros into my string. For example, if the first field contains the number '1', I want it to appear as '001' in my String.

I've tried a few things, including the following:



The problem is, of course, that JTextField.getText() returns a String, not an int.

Does anyone know another way to do it?

Thanks,
Jessica
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is, of course, that JTextField.getText() returns a String, not an int.
If the String returned represents a valid double, you can convert it using :
 
Jessica Dancel
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you! That worked. It feels a little kludgey, but it'll do . . .

Thanks again.

Jessica
 
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For your problem as described, Integer.parseInt() would be a better fit - but the idea is the same. And if you're using JDK 5+, you can use a format string to make this a little more compact:

You may also want to ask yourself: what if the user enters something invalid in the text field? Or what if it's blank? Traditionally this has involved catching an exception. Alternately (more elegantly?) you can use JDK 5's Scanner:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!