views:

2370

answers:

5

I need to format a decimal value to 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.

+1  A: 

You want java.text.DecimalFormat

duffymo
+1  A: 

java.text.NumberFormat is probably what you want.

cagcowboy
+3  A: 

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);
Richard Campbell
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
+9  A: 

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 A
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
Thanks for the correction Adeel
Yuval A
+1  A: 

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