如何在Java中使用给定小数点后的位数格式化浮点数?

Bic*_*ick 4 java formatter

Java中从字符串中获取字符串的最佳方法是什么?

Ton*_*ony 6

以下是处理问题的两种方法.

    public static void main(String[] args) {
    final float myfloat = 1F / 3F;

    //Using String.format 5 digist after the .
    final String fmtString = String.format("%.5f",myfloat);
    System.out.println(fmtString);

    //Same using NumberFormat
    final NumberFormat numFormat = NumberFormat.getNumberInstance();
    numFormat.setMaximumFractionDigits(5);
    final String fmtString2 = numFormat.format(myfloat);
    System.out.println(fmtString2);
}
Run Code Online (Sandbox Code Playgroud)