• Post Reply Bookmark Topic Watch Topic
  • New Topic

Formatting values  RSS feed

 
Tom E. Cole
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a situation where I need to format the following number:

12312345123

To the following:

123-12345-123

If the value has less then 11 digits then it should format right justified. For example:

1212345123

Would become

12-12345-123

And 112345123 Would become

1-12345-123, etc.

I cannot find a way to do this. I have tried using the format 000-00000-000 and ###-#####-### and ###-#####-##0, nothing is getting me anything close to what I want.



This outputs 12312345123--



This also outputs 12312345123--



You guessed it 12312345123--.

I am lost in what I think should be a simple issue to resolve. The issue is that while this is one example, the format could be anything (user defined). In my current example I am being given the format 000-00000-000.

Any help would be appreciated.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, you're not formatting a number. You're formatting a String that happens to be composed only of digits. With DecimalFormat, you may be able to select the thousands separator, but there may be limitations on which characters are allowed, and it ignores all but the first occurence of it, so you'll always get the same number of digits between those separators (if you can even control that at all). You can't say "format this number into N digits then a separator then M digits then a separator then P digits." It's simply not what the class was meant for.

You may want to use regex via String's replaceAll() method, or you may just want to do the character iteration and insertion yourself.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!