0

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

2
  • Have you looked at the Java Formatter object? docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html Commented Jun 18, 2012 at 13:49
  • The only thing I can think of is modulo % the number and plug in the formatter string. As for revert it back, replaceAll("-", "") and parseInt are the solution. Commented Jun 18, 2012 at 13:50

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

+1 exactly what I was thinking about posting,but you beat me to it.
@phatfingers Thanks, I figured this was probably going to be my only option, was just hoping java had something much simpler.
1

Java does have a String.format method.

Then use replace all for converting back.

Comments

0

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.

1 Comment

Yes this is exactly what I planned to do, I was just hoping for a simple formatter, but it's looking like String.format is my simplest option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.