Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format floating point number with leading zeros [duplicate]

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);
like image 771
principal-ideal-domain Avatar asked May 06 '15 16:05

principal-ideal-domain


People also ask

How do you add leading zeros to numbers or text with uneven lengths JS?

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.

How do I keep last 0s after decimal point for double data type in Java?

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.

How to show zeros before a number in Excel?

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.


2 Answers

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);
like image 155
Alex Salauyou Avatar answered Sep 28 '22 07:09

Alex Salauyou


DecimalFormat formatter = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
formatter.applyPattern("000.###");
System.out.format(formatter.format(1.23456789));

Result:

001.234

Demo

like image 23
Stéphane GRILLON Avatar answered Sep 28 '22 06:09

Stéphane GRILLON