如何在“+”后使用 space 格式化打印双精度值
How do I format printing a double value with a space after "+"
我使用:
"%+.1f"
并得到:
+6.0
+2.5
-2.2
但需要:
+ 6.0
+ 2.5
- 2.2
是否可以使用标准 java 格式化程序?
我不这么认为,而且我在 the Formatter docs 中也没有提到它,但你总是可以使用类似的东西:
public static String formattedFloat(float f) {
return String.format("%s %.1f", f >= 0 ? "+" : "-", Math.abs(f));
}
// Example
System.out.println(formattedFloat(-2.21234f);
// prints "- 2.2"
System.out.println(formattedFloat(6f);
// prints "+ 6.0"
标志是简单的标志集on/off,不是输出的不同部分。 System.out.format(..)
使用 java.util.Formatter 但我看不到任何选项
在同一个函数调用中更改它。你最好的选择是获得输出
在一个字符串中并手动格式化它。
我使用:
"%+.1f"
并得到:
+6.0
+2.5
-2.2
但需要:
+ 6.0
+ 2.5
- 2.2
是否可以使用标准 java 格式化程序?
我不这么认为,而且我在 the Formatter docs 中也没有提到它,但你总是可以使用类似的东西:
public static String formattedFloat(float f) {
return String.format("%s %.1f", f >= 0 ? "+" : "-", Math.abs(f));
}
// Example
System.out.println(formattedFloat(-2.21234f);
// prints "- 2.2"
System.out.println(formattedFloat(6f);
// prints "+ 6.0"
标志是简单的标志集on/off,不是输出的不同部分。 System.out.format(..)
使用 java.util.Formatter 但我看不到任何选项
在同一个函数调用中更改它。你最好的选择是获得输出
在一个字符串中并手动格式化它。