简体   繁体   English

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

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

What is the best way in Java to get a string out of a float, that contains only X digits after the dot? Java 中从浮点数中获取字符串的最佳方法是什么,该字符串在点后仅包含 X 位数字?

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);
}
  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注意: %n是换行符

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

Is Float.toString() what you're after? Float.toString()是你所追求的吗?

See also the Formatter class for an alternative method.另请参阅Formatter程序 class 了解替代方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM