85

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.

Ola Ström
  • 2,878
  • 3
  • 18
  • 33
richs
  • 4,621
  • 10
  • 42
  • 55

6 Answers6

188

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"
mostar
  • 4,637
  • 1
  • 27
  • 45
  • 27
    This may not be the correct answer to the question asked, but it's the answer I came here to find. Thanks! – milosmns Jan 10 '16 at 18:54
96

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);
Richard Campbell
  • 3,580
  • 22
  • 18
  • 4
    Follow the same example you will get the wrong result. You need to use the RoundingMode.DOWN for this particular example. Otherwise, it uses HALF_EVEN. No, negative though. – Adeel Ansari Jan 12 '09 at 03:40
41

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));
Yuval Adam
  • 155,852
  • 90
  • 298
  • 388
  • No negatives, but your code fails for the very first example, given by the original poster. Need to use RoundingMode.DOWN, otherwise it uses HALF_EVEN by default, I suppose. – Adeel Ansari Jan 12 '09 at 03:41
3

java.text.NumberFormat is probably what you want.

cagcowboy
  • 28,703
  • 10
  • 67
  • 91
2

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.

Brian Clapper
  • 24,425
  • 7
  • 63
  • 65
1

You want java.text.DecimalFormat

duffymo
  • 299,921
  • 44
  • 364
  • 552