-1

Say we have a number

int number = 1234

and I want to use formatting to extract the final two digits as a string 34. How can one accomplish that?

I attempted:

String extraction = String.format("%d", number)

but this simply copies the entire number. I'm new to the syntax used by the formatter and can't seem to figure out the syntax that can go inside the characters of a number (or a String, for that matter) and pull them out. I've found a solution using charAt methods but am particularly curious about whether it's possible to accomplish it using formatting techniques.

0

1 Answer 1

4

Going via a String is inefficient and unnecessary to extract the last two digits of an integer.

Simply:

int lastTwoDigits = number % 100;

If you do want to go via a String, you can use:

String s = Integer.toString(number);
s = s.substring(s.length() - 2);
int lastTwoDigits = Integer.parseInt(s);

(note that this handles -ve numbers slightly differently to the first suggestion).

3
  • does the Stringapproach assume that the number is a positive integer greater than 10 ? Commented Nov 10, 2017 at 12:06
  • The concept of "the last two digits of a number" only really makes sense if that number has at least two digits. And handling of negative numbers isn't defined. These are really cases which should be left up to OP to decide how they should be handled. Commented Nov 10, 2017 at 12:08
  • Thank you. it seems to me that it is not possible using formatting techniques to extract certain parts of strings/integers
    – kapython
    Commented Nov 10, 2017 at 13:22

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.