Search code examples
javaformatting

What's Best Way of Formatting Decimal Numbers in Java?


I've been looking for formatting decimal numbers easily as in JavaScript by using toFixed().

What's your suggestion?


Solution

  • Using String.format is likely to be the simplest.

    var num = new Number(13.3714);
    document.write(num.toFixed()+"<br />");
    document.write(num.toFixed(1)+"<br />");
    document.write(num.toFixed(3)+"<br />");
    document.write(num.toFixed(10));
    

    in Java

    double num = 13.3714;
    // Uses String.format()
    System.out.printf(
              "%f<br />" +
              "%.1f<br />" +
              "%.3f<br />" +
              "%.10f<br />", num, num, num, num);