我需要使用加号将输入的数字字符串与掩码右对齐。
例如:
String input = "893";
String mask = "&&&&&&";
应该返回
String output = "+++893";
我对如何使用 NumberFormat 和/或 DecimalFormat 实现这一点感到非常困惑,因为我以前没有使用过它们。任何帮助将不胜感激。
最佳答案
如果您需要使用 DeciamlFormat,您可以使用:
int input = 893;
DecimalFormat decFormat = new DecimalFormat("000000"); //as many palces as you need
String output = decFormat.format(input);
然后用+号替换所有前导零。
String.format("%06d", input); //also gives you leading zeros
如果您总是想要 6 个位置,您仍然需要检查输出是否太长。
关于java - Java 中的右对齐字符串 NumberFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865314/