Search code examples
javastringroundingprecisionfloating-accuracy

How to Java String.format with a variable precision?


I'd like to allow the user to vary the precision of a String generated from a double. 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).

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

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.


Solution

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

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

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