Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Java String.format with a variable precision?

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

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.

like image 372
Willi Ballenthin Avatar asked Feb 20 '10 04:02

Willi Ballenthin


People also ask

What is %s in Java?

the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.

What does %n do in Java?

By using %n in your format string, you tell Java to use the value returned by System. getProperty("line. separator") , which is the line separator for the current system.

Can you format strings in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.


2 Answers

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.

like image 92
vicatcu Avatar answered Sep 28 '22 08:09

vicatcu


You can use the DecimalFormat class.

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) 
like image 42
Willi Mentzel Avatar answered Sep 28 '22 08:09

Willi Mentzel