Java decimal formatting using String.format?

204,943

Solution 1

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);

Solution 2

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"

Solution 3

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));

Solution 4

java.text.NumberFormat is probably what you want.

Solution 5

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.

Share:
204,943

Related videos on Youtube

richs
Author by

richs

Updated on February 12, 2020

Comments

  • richs
    richs over 4 years

    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.

  • Adeel Ansari
    Adeel Ansari over 15 years
    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
    Adeel Ansari over 15 years
    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.
  • milosmns
    milosmns over 8 years
    This may not be the correct answer to the question asked, but it's the answer I came here to find. Thanks!