Number Formating using regular expression and format method of String class

14 / Dec / 2010 by Salil 0 comments

Hey guys, I found something very useful, so sharing it here.
In one of my project there was a requirement to create a fixed length user-id. Let’s say it was 5 characters ID.


So in other words we required to convert -
‘123’ to ‘00123’ and ‘1000’ to ‘01000’ and ‘12345’ will remain ‘12345’.
It appears very simple, but the thing is how quick we do this.


Earlier I thought to do this by calculating the length of id and prefixing required number of zeros.


Alternate single-line and faster solution is –

      // following will return a String with size of 5 characters and prefixes zeros (if id has digits lesser than 5).
         String.format('%05d', id)
      // Note down, id is a digit here.

That’s all. . isn’t it nice?. We can utilize it at many places like – converting date from ‘1-1-2010′ to ’01-01-2010′.
Idea is to introduce such kind of utility. If you already knew this, please ignore :-)
please open the ideas – if you know something better than this.


cheers!
salil at IntelliGrape dot com

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -