Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top