如何格式化字符串以打印 4 位数字和 2 位小数
How to format a string so that it prints 4 digits and 2 decimals
我正在尝试打印一个始终为 4 位数字且具有 2 个小数位的双精度数。
例如,如果号码是 105.456789
我的 String.Format
会打印出 0105.45
我知道 %.2f
允许小数点后两位的问题。
我也明白 %04d
允许 4 位数的问题
但是,我一辈子都想不出如何将两者结合起来。
我试过双人String.format
我试过做一个 String.format
并同时使用 %04d
和 %.2f
System.out.println(String.format("Gross Pay: $%.2f %04d", 105.456789));
我希望输出为 0105.45,但我什至无法编译它
两件事:首先,您的代码可以编译。但它在运行时立即失败:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%04d'
因为:您在格式规范中使用了两个 模式,但只提供了一个值。
是的,%.2f %04d
是 两个 规格,而不是一个。
(请理解这一点:编译时错误和运行时异常之间存在明显区别。理解这种区别很重要。)
回到"real"问题。因此,您必须使用 one 规范,而不是对一个值使用两种模式,例如:
System.out.println(String.format("Gross Pay: $%07.2f", 105.456789));
Gross Pay: 05.46
"trick":"dot"前面的那个需要占到总体想要的长度。总的来说,你想要:4 位数字+点+2 位数字,得到 7 个字符。 0 表示预先填写。
因此您的规格需要以“07”开头。
这将为您提供您想要的:
double num = 105.456789;
System.out.println(String.format("Gross Pay: $%04.0f", num) +
"." + String.valueOf(num).split("\.")[1].substring(0,2));
输出:
Gross Pay: 05.45
解释:
据我所知,String.format
点后的 2 位数不能不四舍五入(如果我错了,请纠正我),所以我建议使用 split
方法。如果你愿意,你可以像我一样把这些都塞进一个声明中,但它不是很漂亮,所以这取决于你。
我正在尝试打印一个始终为 4 位数字且具有 2 个小数位的双精度数。
例如,如果号码是 105.456789
我的 String.Format
会打印出 0105.45
我知道 %.2f
允许小数点后两位的问题。
我也明白 %04d
允许 4 位数的问题
但是,我一辈子都想不出如何将两者结合起来。
我试过双人String.format
我试过做一个 String.format
并同时使用 %04d
和 %.2f
System.out.println(String.format("Gross Pay: $%.2f %04d", 105.456789));
我希望输出为 0105.45,但我什至无法编译它
两件事:首先,您的代码可以编译。但它在运行时立即失败:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%04d'
因为:您在格式规范中使用了两个 模式,但只提供了一个值。
是的,%.2f %04d
是 两个 规格,而不是一个。
(请理解这一点:编译时错误和运行时异常之间存在明显区别。理解这种区别很重要。)
回到"real"问题。因此,您必须使用 one 规范,而不是对一个值使用两种模式,例如:
System.out.println(String.format("Gross Pay: $%07.2f", 105.456789));
Gross Pay: 05.46
"trick":"dot"前面的那个需要占到总体想要的长度。总的来说,你想要:4 位数字+点+2 位数字,得到 7 个字符。 0 表示预先填写。
因此您的规格需要以“07”开头。
这将为您提供您想要的:
double num = 105.456789;
System.out.println(String.format("Gross Pay: $%04.0f", num) +
"." + String.valueOf(num).split("\.")[1].substring(0,2));
输出:
Gross Pay: 05.45
解释:
据我所知,String.format
点后的 2 位数不能不四舍五入(如果我错了,请纠正我),所以我建议使用 split
方法。如果你愿意,你可以像我一样把这些都塞进一个声明中,但它不是很漂亮,所以这取决于你。