如何使用可变精度的Java String.format? [英] How to Java String.format with a variable precision?

查看:232
本文介绍了如何使用可变精度的Java String.format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户输入改变字符串中双重表示的精度。现在我正在尝试这样的事情:

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

但我收到 java.util.UnknownFormatConversionException 。我对这种方法的启发是C printf和此资源(第1.3.1节)。

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

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

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

修改:

我想我可以做类似的事情:

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.

推荐答案

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

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.

如果你想要一个占用8个字符(包括小数点)的格式化小数)你希望小数点后4位数,你的格式字符串应该看起来像%8.4f...

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"...

据我所知,没有原生支持在Java中超出格式字符串是灵活的。

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

这篇关于如何使用可变精度的Java String.format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆