您可以编写一个在数字前打印空格的函数。
如果它们都是4.3f
,我们可以假设每个数字最多占用 8 个字符,所以我们可以这样做:
public static String printDouble(Double number)
{
String numberString = String.format("%4.3f", number);
int empty = 8 - numberString.length();
String emptyString = new String(new char[empty]).replace('\0', ' ');
return (emptyString + numberString);
}
输入:
public static void main(String[] args)
{
System.out.println(printDouble(1.123));
System.out.println(printDouble(12.423));
System.out.println(printDouble(0.123));
System.out.println(printDouble(123.344));
System.out.println(printDouble(1.100));
}
输出:
run:
1,123
12,423
0,123
123,344
1,100
BUILD SUCCESSFUL (total time: 0 seconds)