Java decimal formatting using String.format?

JavaFormattingDecimal

Java Problem Overview


I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4.

So for example

"34.49596" would be "34.4959" 
"49.3" would be "49.30"

Can this be done using the String.format command?
Or is there an easier/better way to do this in Java.

Java Solutions


Solution 1 - Java

Yes you can do it with String.format:

String result = String.format("%.2f", 10.0 / 3.0);
// result:  "3.33"

result = String.format("%.3f", 2.5);
// result:  "2.500"

Solution 2 - Java

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);

Solution 3 - Java

Here is a small code snippet that does the job:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

Solution 4 - Java

java.text.NumberFormat is probably what you want.

Solution 5 - Java

NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode() method. You can use it to control how rounding or truncation is applied during formatting.

Solution 6 - Java

You want java.text.DecimalFormat

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrichsView Question on Stackoverflow
Solution 1 - JavamostarView Answer on Stackoverflow
Solution 2 - JavaRichard CampbellView Answer on Stackoverflow
Solution 3 - JavaYuval AdamView Answer on Stackoverflow
Solution 4 - JavacagcowboyView Answer on Stackoverflow
Solution 5 - JavaBrian ClapperView Answer on Stackoverflow
Solution 6 - JavaduffymoView Answer on Stackoverflow