This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Text Formatting  RSS feed

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are there any methods in J2ME that I can use to format a String?

I need to be able to pad a number so that zeros are added to the front if it if it is less than five digits.

For example, "123" would become "00123", etc.

In the .NET Compact Framework, you can use this method: ToString("00000")

Thanks,

Drew
 
Roseanne Zhang
Ranch Hand
Posts: 1953
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think there is any, I wrote my own method.
 
Marc Peabody
pie sneak
Sheriff
Posts: 4727
Mac Ruby VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String value = "123";
StringBuffer sb = new StringBuffer("00000");
sb.replace( sb.length() - value.length(), sb.length(), value);

This is the best way I can think of. You could use 5 in place of sb.length() here but doing it this way will allow you to change "00000" to more digits without breaking the code.
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very nice.

Much cleaner than my method, which was to use StringBuffer.append().

Thanks!

Drew
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!