简体   繁体   中英

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.

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.

您可以尝试以下操作:如果遮罩的长度大于输入的长度,请求差并在输入的前面添加许多加号。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM