90

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
5,4776 gold badges32 silver badges51 bronze badges
asked Jan 11, 2009 at 23:08

6 Answers 6

199

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"
answered Oct 4, 2012 at 22:29
Sign up to request clarification or add additional context in comments.

1 Comment

This may not be the correct answer to the question asked, but it's the answer I came here to find. Thanks!
98

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);
answered Jan 11, 2009 at 23:13

1 Comment

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

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));
answered Jan 11, 2009 at 23:16

1 Comment

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

java.text.NumberFormat is probably what you want.

answered Jan 11, 2009 at 23:11

Comments

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.

answered Jan 12, 2009 at 0:49

Comments

1

You want java.text.DecimalFormat

answered Jan 11, 2009 at 23:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.