I'm trying to get the decimal 8.6
to render to a left zero-padded string ie 08.6
.
Why doesn't the following seem to work?
double number = 8.6;
String.format("%03.1f", number); //expect "08.6", get "8.6"
The formatting string seems to be correct. What am I doing wrong?
It is giving you a left zero-padded floating point output, it's just that the field width of 3
includes the decimal point and the fractional portion (and the sign, if it's negative), so you need to use %04.1f
instead for that particular value.
The output of:
public class Test {
public static void main(String[] args) {
double number = 8.6;
System.out.println(String.format("%04.1f", number));
}
}
is:
08.6
你需要给为%04.1f
得到输出08.6
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.