Surround your % with single quotes:
DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
Pergunta
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 %
Solução
Surround your % with single quotes:
DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
Outras dicas
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 %
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.