如何使用可变精度的 Java String.format?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2301047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:51:02  来源:igfitidea点击:

How to Java String.format with a variable precision?

javastringroundingprecisionfloating-accuracy

提问by Willi Ballenthin

I'd like to vary the precision of a double representation in a string I'm formatting based on user input. Right now I'm trying something like:

我想根据用户输入改变我正在格式化的字符串中双重表示的精度。现在我正在尝试类似的东西:

String foo = String.format("%.*f\n", precision, my_double);

however I receive a java.util.UnknownFormatConversionException. My inspiration for this approach was C printf and this resource(section 1.3.1).

但是我收到了一个java.util.UnknownFormatConversionException. 我对这种方法的灵感来自 C printf 和这个资源(第 1.3.1 节)。

Do I have a simple syntax error somewhere, does Java support this case, or is there a better approach?

我在某处有一个简单的语法错误,Java 支持这种情况,还是有更好的方法?

Edit:

编辑:

I suppose I could do something like:

我想我可以这样做:

String foo = String.format("%." + precision + "f\n", my_double);

but I'd still be interested in native support for such an operation.

但我仍然对这种操作的本机支持感兴趣。

采纳答案by vicatcu

You sort of answered your own question - build your format string dynamically... valid format strings follow the conventions outlined here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax.

你有点回答你自己的问题 - 动态构建你的格式字符串......有效的格式字符串遵循此处概述的约定:http: //java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter .html#syntax

If you want a formatted decimal that occupies 8 total characters (including the decimal point) and you wanted 4 digits after the decimal point, your format string should look like "%8.4f"...

如果您想要一个占 8 个字符(包括小数点)的格式化小数,并且您想要小数点后 4 个数字,那么您的格式字符串应该类似于“%8.4f”...

To my knowledge there is no "native support" in Java beyond format strings being flexible.

据我所知,除了灵活的格式字符串之外,Java 中没有“本机支持”。

回答by Gerdi

Why not :

为什么不 :

String form = "%."+precision+"f\n";
String foo = String.format(form, my_double);

or :

或者 :

public static String myFormat(String src, int precision, Object args...)
{
    String form = "%."+precision+"f\n";
    return String.format(form, args);
}

回答by Willi Mentzel

You can use the DecimalFormatclass.

您可以使用DecimalFormat类。

double d1 = 3.14159;
double d2 = 1.235;

DecimalFormat df = new DecimalFormat("#.##");

double roundedD1 = df.format(d); // 3.14
double roundedD2 = df.format(d); // 1.24

If you want to set the precision at run time call:

如果要在运行时设置精度调用:

df.setMaximumFractionDigits(precision)