如何在Java中格式化一个带有小数点后给定位数的浮点数?

发布于 2024-11-29 06:32:00 字数 45 浏览 7 评论 0原文

Java中从浮点中获取字符串的最佳方法是什么,该字符串在点后仅包含X个数字?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小梨窩很甜 2024-12-06 06:32:00

这里有两种处理该问题的方法。

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

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);
}
我的痛♀有谁懂 2024-12-06 06:32:00
  double pi = Math.PI;
  System.out.format("%f%n", pi);    //  -->  "3.141593"    
  System.out.format("%.3f%n", pi);  //  -->  "3.142"

注意: %n 用于换行

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

  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

虫児飞 2024-12-06 06:32:00

Float.toString ()你在追求什么?

另请参阅 Formatter 类的替代方法。

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

See also the Formatter class for an alternative method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文