Java 如果数字为零,String.format可以删除它们吗?
我正在制作秒表,我只想在小时数大于0时显示一个字段。 目前我是这样解决的,有没有较短的方法Java 如果数字为零,String.format可以删除它们吗?,java,string,formatting,format,string-formatting,Java,String,Formatting,Format,String Formatting,我正在制作秒表,我只想在小时数大于0时显示一个字段。 目前我是这样解决的,有没有较短的方法 String timeLeftFormatted = ""; if (hours > 0) { timeLeftFormatted = String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds); } else { timeLef
String timeLeftFormatted = "";
if (hours > 0) {
timeLeftFormatted = String.format(Locale.getDefault(),
"%d:%02d:%02d", hours, minutes, seconds);
} else {
timeLeftFormatted = String.format(Locale.getDefault(),
"%02d:%02d", minutes, seconds);
}
有多种方法可以做到这一点,我能想到的最简单的方法是:
timeLeftFormatted=String.format(Locale.getDefault(),
“%s:%02d:%02d”,小时数>0?字符串。值(小时):“”,分钟,秒)代码>
编辑:
以类似的方式,您还可以根据hours
是否大于零来修改未格式化字符串本身。有一个技巧,使用参数_index
的文档显示格式说明符具有以下语法:
%[argument_index$][flags][width][.precision]转换
通过使用argument\u index
,您可以跳过未使用的参数,即使用固定参数列表,您可以将格式字符串本身替换为仅使用部分值
使用您的示例和三元条件运算符,为清晰起见,每个参数显示一行:
String timeLeftFormatted = String.format(
Locale.getDefault(),
(hours > 0 ? "%1$d:%2$02d:%3$02d" : "%2$02d:%3$02d"),
hours,
minutes,
seconds
);
也可以这样写:
String timeLeftFormatted = String.format((hours > 0 ? "%1$d:" : "") + "%2$02d:%3$02d",
hours, minutes, seconds);
非常感谢。你知道格式化程序是否有办法直接在格式字符串中表达这一点吗?十进制转换有填充和前导空格选项,但不包括/放弃基于值的转换。这是一个相当大的问题,我没有发现我的问题,所以我认为在这里找到答案是一个好主意。