我想在 Java 中格式化 3 位 float ,使它们垂直排列,如下所示:
123.45
99
23.2
45
当我使用 DecimalFormat 类时,我很接近,但我想在项目有 1 位或 2 位数字时插入空格。
我的代码:
DecimalFormat formatter = new java.text.DecimalFormat("####.##");
float [] floats = [123.45, 99.0, 23.2, 45.0];
for(int i=0; i<floats.length; i++)
{
float value = floats[i];
println(formatter.format(value));
}
它产生:
123.45
99
23.2
45
如何打印它,以便除第一行以外的所有行都移动一个空格?
最佳答案
尝试使用 String.format()
(JavaDoc):
public static void main(String args[]){
String format = "%10.2f\n"; // width == 10 and 2 digits after the dot
float [] floats = {123.45f, 99.0f, 23.2f, 45.0f};
for(int i=0; i<floats.length; i++) {
float value = floats[i];
System.out.format(format, value);
}
输出是:
123.45
99.00
23.20
45.00
关于java - 使用相同数量的填充格式化数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3339516/