문제

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?

도움이 되었습니까?

해결책

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%  |

다른 팁

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top