Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

width specify in printf  RSS feed

 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ranchers,

i have to specify output like


i have to specify 4 spaces in between of numbers with condition as no space before first and last number of line

i am using code like



but with this there are four spaces before first number of each line i.e. 1 and 5.


 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With "%4d" you are actually giving 4 positions for the value you are printing. Since on position is occupied by the value itself, you get only 3 spaces between values.
You can use similar thing to accomplish what you want:
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
naveen yadav wrote:hi ranchers,

i have to specify output like


i have to specify 4 spaces in between of numbers with condition as no space before first and last number of line


I assume you just mean no spaces before the first number. If you had no spaces before the last number, you would get


Also, will they always be single-digit numbers? If not, how do you want them aligned? The normal approach would be to right-align them:


which you can get with "%5d".

If you left-align them, to have no leading spaces, with "%-5d", it will look like this:


which is less comon, and can make it harder to read them as columns of numbers.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!