Java decimal string format

I need to format the decimal value in a line where I always show 2 decimal places and at most 4 in leasing.

eg,

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

+45
java string-formatting
Jan 11 '09 at 23:08
source share
6 answers

You want java.text.DecimalFormat.

 DecimalFormat df = new DecimalFormat("0.00##"); String result = df.format(34.4959); 
+59
Jan 11 '09 at 23:13
source share
— -

Yes, you can do this with String.format :

 String result = String.format("%.2f", 10.0 / 3.0); // result: "3.33" result = String.format("%.3f", 2.5); // result: "2.500" 
+108
04 Oct '12 at 22:29
source share

Here is a small piece of code 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)); 
+37
Jan 11 '09 at 23:16
source share

java.text.NumberFormat is what you want.

+3
Jan 11 '09 at 23:11
source share

Do you want java.text.DecimalFormat

+1
Jan 11 '09 at 23:11
source share

NumberFormat and DecimalFormat are definitely what you want. Also pay attention to the NumberFormat.setRoundingMode() method. You can use it to control rounding or truncation when formatting.

+1
Jan 12 '09 at 0:49
source share



All Articles