Search code examples
javadouble

How to format a double with leading zero and decimals in Java


Requirements:

  • Leading zero (total 2 length) before the Dot

  • 3 decimals

    // Example 1 Input: double d = 1.2345 Expected output: 01.234

    // Example 2 Input: double d = 11.2345 Expected output: 11.234

In C#, I can use:

double.ToString("00.###")

In Java:

String.format("%.3f", 1.2345) ->  1.234 -> No leading zero.

Solution

  • Try DecimalFormat.

    DecimalFormat df = new DecimalFormat("00.###");
    String formatted = df.format(1.2345); 
    System.out.println( formatted );
    

    Result:

    01.234