Why does
System.out.format("%03.3f", 1.23456789);
print 1.235
instead of 001.235
?
How has my format
string to look like to get 001.235
as output of the following code line?
System.out.format(format, 1.23456789);
Use the padStart() method to pad the string with leading zeros. The padstart() method will add leading zeros to the start of the string until it reaches the specified target length.
To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.
Use the "0"# format when you want to display one leading zero. When you use this format, the numbers that you type and the numbers that Microsoft Excel displays are listed in the following table. Example 2: Use the "000"# format when you want to display three leading zeros.
Number after %0
here defines full width including decimal point, so you need to change it to 7
:
System.out.format("%07.3f", 1.23456789);
DecimalFormat formatter = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
formatter.applyPattern("000.###");
System.out.format(formatter.format(1.23456789));
Result:
001.234
Demo
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