Reputation: 7788
I'm wondering if there is a String formatter in java similar to the java DecimalFormat("0.#")
I have the following set of numbers that needs to be masked with dashes, "00-0000-00", I was hoping there would be a formatter that would enable me to do this in a similar way you handle DecimalFormat("00-0000-00"). If such a method doesn't exist, could someone please provide an example of an alternate solution.
I need to strip the dashes when saving to the database and add them back in when retrieving them from the database.
Thanks
Upvotes: 0
Views: 4958
Reputation: 10250
Have you looked at String.format("%2d-%4d-%2d", int1, int2, int3)
?
Example:
int n = 12345678;
String formatted = String.format("%2d-%4d-%2d", n / 1000000, (n / 100) % 10000, n % 100);
int orig = Integer.valueOf(formatted.replace("-", ""));
System.out.println(String.format("formatted=%s, orig=%d", formatted, orig));
// formatted=12-3456-78, orig=12345678
Upvotes: 6
Reputation: 711
Write a custom method and its reverse. The former will be called before adding to your db and the latter after retrieving your db. Shouldn't be much of problem, I believe.
Upvotes: 0
Reputation: 6043
Java does have a String.format method.
Then use replace all for converting back.
Upvotes: 1