Question

I am trying to print a percentage sign using printf. When I use the following:

System.out.printf("%-3d%%\n",10);
System.out.printf("%-3d%%\n",100);
System.out.printf("%-3d%%\n",0);

I end up with:

10 %  
100%
0  %

How can I achieve the following

10%   - 1 space after % sign
100%  - no space 
0%    - 2 spaces after % sign

Any ideas?

Was it helpful?

Solution

try

    System.out.printf("%-4.4s\n",10 + "%");
    System.out.printf("%-4.4s\n",100+ "%");
    System.out.printf("%-4.4s\n",0+ "%");

this can be verified with

    System.out.printf("%-4.4s|\n",10 + "%");
    System.out.printf("%-4.4s|\n",100 + "%");
    System.out.printf("%-4.4s|\n",0+ "%");

which produces

10% |
100%|
0%  |

OTHER TIPS

try with DecimalFormat..

    DecimalFormat df=new  DecimalFormat("###'%'");
    System.out.printf("%s\n",df.format(10));
    System.out.printf("%s\n",df.format(1));
    System.out.printf("%s\n",df.format(100));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top