0

I need to right align an input string of digits with a mask using plus symbols.

For example:

    String input = "893";
    String mask = "&&&&&&";

should return

    String output = "+++893";

I'm very confused on how to implement this with NumberFormat and or DecimalFormat as I haven't used them before. Any help would be appreciated.

3
  • 1
    What if the mask is shorter than the input? Do you truncate or ignore? Commented Feb 18, 2014 at 21:10
  • The I would ignore. But I already check for that. Commented Feb 18, 2014 at 21:12
  • What about String.format("%-6d", input)? Commented Feb 18, 2014 at 21:15

2 Answers 2

1

If you need to use DeciamlFormat you could use:

int input = 893;
DecimalFormat decFormat = new DecimalFormat("000000"); //as many palces as you need
String output = decFormat.format(input);

And then replace all leading zeros with + sign.

String.format("%06d", input); //also gives you leading zeros 

You still have to check if the output is too long, if you always want 6 places.

Sign up to request clarification or add additional context in comments.

Comments

0

You could try this: If the length of the mask is greater than the length of the input, take the difference and add that many plus signs to the front of the input.

3 Comments

Although I don't get the point of the mask then. You could simply have a desired length
Yeah that was my first idea but I just wanted to ask if there was a more elegant way using NumberFormat.
the mask will also be part of the input.

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.