'Printing out 3 of numbers in java

The output value is 100000 to 10 random natural numbers What should I do to print out only from the right end to the third? And if you print it out with multiple of ten, an error appears so, if we get a multiple of 10, i want to put out 010 something

for example, input -> 6545 output -> 545, input -> 27 output -> 027

and i'm using java. pls help me



Solution 1:[1]

Assuming your inputs are actually ints:

System.out.printf("%03d",inputvalue%1000); 

should give the result you want:

  • "%03d" forces output with zero padding
  • inputvalue%1000 calculates the remainder of division by 1000 (modulo), which will chop off all digits to the left of the three last

Solution 2:[2]

You can transform an Int to a String with String.valueOf(i). Then, you only have to take the 3 last characters of the string and adding 0. Because your "027" is a String, it isn't an Int

Solution 3:[3]

    public static void main(String... args) {
  
    Random rand = new Random();
    int upperbound = 100000;
    int lowerbound = 10;
    int random_integer = rand.nextInt(upperbound - lowerbound) + lowerbound;

    String output = String.valueOf(random_integer);
    String finaloutput = output;
    if (output.length() <= 3) {

        for (int i = 0; i < 3 - output.length(); i++) {
            finaloutput = "0" + finaloutput;
        }
    } else {
        finaloutput = output.substring(0, 3);
    }

    System.out.println(random_integer + "->" + finaloutput);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fvu
Solution 2 paul
Solution 3 DereckChamboko