PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 14, 2022

[FIXED] How to Count Integers With Padded Zeros

 August 14, 2022     format, java, output, string     No comments   

Issue

I want to count from 1 to 10 with a variable width.

Example for width: 4

Count Should Be:

0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 ---> Note that it's not 00010

Example for width: 2

Count Should Be:

01 ... 09 10 ---> Not 010

I've tried the following:

First attempt

for(int i = 1; i <= 10; ++i) {
   System.out.println("0".repeat(width-1) + i);
}

Second attempt

String output = String.format("%04d", 1);

These do not properly format numbers as the number of digits changes.


Solution

You can create a format String with a variable length of format specifier. Adjust the width variable to whatever leading 0s you need.

int width = 2;
String format = "%0"+width+"d";

for(int i = 1; i <= 10; i++)  {
    String output = String.format(format, i);
    System.out.println(output);
}


/* Output:
01
02
03
04
05
06
07
08
09
10
*/


Answered By - Abdullah Leghari
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing