Search code examples
javastringnumber-formattingright-align

Right Align String NumberFormat in Java


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.


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.