• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Formatting values

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic