1

i have a function that generates 2 random numbers and determine the number with the highest number of digits. What i want is to add zeros in the number with lower digits to make them equal. how can i do that? for example First number: 340 Second Number: 3

i want the result to be 340 and 003.

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
beginner
  • 2,024
  • 5
  • 43
  • 76

2 Answers2

3
int lengthOfBigger = String.valueOf(biggerNumber).length();
String pattern = "%0" + lengthOfBigger + "d";

String smallerNumberPadded = String.format(pattern, smallerNumber);

Taken mostly from this question

EDIT:

For just spaces change pattern to

String pattern = "% " + lengthOfBigger + "d";
Community
  • 1
  • 1
Joe Maher
  • 5,354
  • 5
  • 28
  • 44
1

you can use System.out.printf("%03d", valueName);

what happens is that any value that will be printed would be at least 3 numbers in length and it will print preceding 0s.