在C语言中,printf()语句允许在参数列表中提供精度长度。
printf("%*.*f", 7, 3, floatValue);
这里的星号将分别替换为第一个和第二个值。
我正在寻找在Android/Java中等效的方法;String.format()会引发异常。
编辑:感谢@Tenner;它确实有效。
printf("%*.*f", 7, 3, floatValue);
这里的星号将分别替换为第一个和第二个值。
我正在寻找在Android/Java中等效的方法;String.format()会引发异常。
编辑:感谢@Tenner;它确实有效。
我使用
int places = 7;
int decimals = 3;
String.format("%" + places + "." + decimals + "f", floatValue);
有点丑陋(字符串拼接使其性能不佳),但它能正常工作。
System.out.print(String.format("%.1f",floatValue));
这将使用1位小数精度打印floatValue。
String f = String.format("%%%d.%df", 7, 3);
System.out.println(f);
System.out.format(f, 111.1111);
%7.3f
111,111
您还可以使用类似这样的小助手:
public static String deepFormatter(String format, Object[]... args) {
String result = format;
for (int i = 0; i != args.length; ++i) {
result = String.format(result, args[i]);
}
return result;
}
111,111
。deepFormatter("%%%d.%df", new Object[] {7, 3}, new Object[] {111.1111});
它不像printf那样美观,输入格式可能会变得混乱,但你可以做更多的事情。
就像这样...
%AFWPdatatype
A
- 参数数量
F
- 标志位
W
- 宽度
P
- 精度
String.format("%.1f",float_Val);