I'm trying to get the decimal 8.6
to render to a left zero-padded string i.e. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With