How can I format a float in Java with a given number of digits after the decimal point?

拜拜、爱过 提交于 2019-12-23 12:37:44

问题


What is the best way in Java to get a string out of a float, that contains only X digits after the dot?


回答1:


Here are two ways of dealing with the problem.

    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);
}



回答2:


  double pi = Math.PI;
  System.out.format("%f%n", pi);    //  -->  "3.141593"    
  System.out.format("%.3f%n", pi);  //  -->  "3.142"

note: %n is for newline

Source: http://download.oracle.com/javase/tutorial/java/data/numberformat.html




回答3:


Is Float.toString() what you're after?

See also the Formatter class for an alternative method.



来源:https://stackoverflow.com/questions/7056866/how-can-i-format-a-float-in-java-with-a-given-number-of-digits-after-the-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!