Stop DecimalFormat with percentage sign from moving the decimal
Asked Answered
C

3

21

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 %
Citizen answered 14/1, 2014 at 20:17 Comment(0)
B
37

Surround your % with single quotes:

DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
Boxwood answered 14/1, 2014 at 20:20 Comment(7)
I see that it works, but why does this work? What are the single quotes doing?Citizen
@Citizen From the JavaDoc (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.Disorganize
@Citizen 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 SimpleDateFormatBoxwood
Ahh I see. So a SimpleDateFormat with MMM d, 'Y' would look like Jan 14, Y. Makes sense.Citizen
Option B: don't fight the percent operator, and format the value (d/100) :)Overstrung
@Overstrung well MikeB addresses that in a cleaner way I guess :)Boxwood
@JVMATL, truth is my old code is littered with / 100s and * 100s 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.Citizen
D
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 %
Disorganize answered 14/1, 2014 at 20:20 Comment(0)
F
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.

Futtock answered 5/12, 2017 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.