20

Is there a way to prevent a DecimalFormat object from automatically moving the decimal place two places to the right?

This code:

double d = 65.87;
DecimalFormat df1 = new DecimalFormat(" #,##0.00");
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
System.out.println(df1.format(d));
System.out.println(df2.format(d));

produces:

65.87
6,587.00 %

But I'd like it to produce:

65.87
65.87 %
ryvantage
  • 13,064
  • 15
  • 63
  • 112

3 Answers3

35

Surround your % with single quotes:

DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
  • I see that it works, but why does this work? What are the single quotes doing? – ryvantage Jan 14 '14 at 20:25
  • 3
    @ryvantage From the JavaDoc (http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) - `Many characters in a pattern are taken literally; they are matched during parsing and output unchanged during formatting. Special characters, on the other hand, stand for other characters, strings, or classes of characters. They must be quoted, unless noted otherwise, if they are to appear in the prefix or suffix as literals.` – Mike B Jan 14 '14 at 20:26
  • @ryvantage MikeB did beat me to the explanation but that is effectively escaping your arbitrary chars. Same is true for other Classes of Pattern matching - like `SimpleDateFormat` – StoopidDonut Jan 14 '14 at 20:29
  • Ahh I see. So a `SimpleDateFormat` with `MMM d, 'Y'` would look like `Jan 14, Y`. Makes sense. – ryvantage Jan 14 '14 at 20:36
  • Option B: don't fight the percent operator, and format the value `(d/100)` :) – JVMATL Jan 14 '14 at 21:12
  • 1
    @JVMATL well MikeB addresses that in a cleaner way I guess :) – StoopidDonut Jan 14 '14 at 21:18
  • @JVMATL, truth is my old code is littered with `/ 100`s and `* 100`s as I have always been dancing around this problem. Knowing this, I think I will always carry percentages as their full value because deciding "when" to do `/ 100` (or `* 100`) has always been frustrating. – ryvantage Jan 14 '14 at 22:41
  • Thanks you @PopoFibo – Mona Oct 09 '16 at 12:53
7

By default when you use a % in your format string the value to be formatted will be first multiplied by 100. You can change the multiplier to 1 using the DecimalFormat.setMultiplier() method.

double d = 65.87;
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
df2.setMultiplier(1);
System.out.println(df2.format(d));

produces

 65.87 %
Mike B
  • 5,390
  • 2
  • 23
  • 45
0

This is how I do it:

// your double in percentage:
double percentage = 0.6587;

// how I get the number in as many decimal places as I need:
double doub = (100*10^n*percentage);
System.out.println("TEST:   " + doub/10^n + "%");

Where n is the number of decimal places you need.

I know this isn't the cleanest way but it works.

Hope this helps.