86

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
  • 4,136
  • 5
  • 22
  • 41
richs
  • 4,699
  • 10
  • 43
  • 56

6 Answers6

190

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,723
  • 2
  • 28
  • 45
  • 29
    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
95

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);
Richard Campbell
  • 3,591
  • 23
  • 18
  • 5
    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
  • 161,610
  • 92
  • 305
  • 395
  • 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
  • 30,012
  • 11
  • 69
  • 93
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
  • 25,705
  • 7
  • 65
  • 65
1

You want java.text.DecimalFormat

duffymo
  • 305,152
  • 44
  • 369
  • 561