Stop DecimalFormat with a percent sign from decimal movement

Is there a way to prevent the 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)); 

gives:

 65.87 6,587.00 % 

But I would like it to produce:

 65.87 65.87 % 
+8
java decimalformat
source share
3 answers

Surround your% with single quotes:

 DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'"); 
+15
source share

By default, when you use % in the format string, the formatted value will first be multiplied by 100. You can change the multiplier by 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 % 
+6
source share

Here 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 is not the cleanest way, but it works.

Hope this helps.

0
source share

All Articles