In this tutorial, we are going to learn about how to get the last 2 digits of a number in Java.
Note: Strings are sequence of characters, where indexes are zero-based. The last character is in position 0, the second in 1, and index of a last character is
To get the last 2 digits of a number, convert the number to a string and call the
substring() method on it, by passing the
string.length()-2 as a argument.
The substring() method returns the last 2 character of a string then convert the result back to a number to get the last 2 digits.
Note: The string.length()-2 givens index of a second character from the end.
Here is an example:
int price = 4239; String priceStr = Integer.toString(price); int lastCharTwoIndex = priceStr.length()-2; // 2nd character index from last int lastTwoDigits = Integer.parseInt(priceStr.substring(lastCharTwoIndex)); System.out.println(lastTwoDigits);
In the example above, on the first step we have converted the number to a string using the
We have passed the
priceStr.length()-2 as argument to the substring() method, so it returns the last 2 characters.
The last step, we used the Integer.parseInt() method to convert it back to a number.