Get the last 3 digits of a number in Java

Get the last 3 digits of a number in Java

In this post we will give you information about Get the last 3 digits of a number in Java. Hear we will give you detail about Get the last 3 digits of a number in JavaAnd how to use it also give you demo for it if it is necessary.

we are going to learn about how to get the last 3 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 string.length()-1 etc.

Get the last 3 digits of a number

To get the last 3 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 3 character of a string then convert the result back to a number to get the last 2 digits.

Note: The string.length()-3 givens index of a third character from the end.

Here is an example:

int price = 421039;String priceStr = Integer.toString(price);int lastThreeIndex = priceStr.length()-3; // 3nd character index from lastint lastThreeDigits = Integer.parseInt(priceStr.substring(lastThreeIndex));System.out.println(lastThreeDigits);

Output:

039

In the example above, on the first step we have converted the number to a string using the Integer.toString() method.

We have passed the priceStr.length()-3 as argument to the substring() method, so it returns the last 3 characters.

The last step, we used the Integer.parseInt() method to convert it back to a number.

or You can get the last 3 digits of a number, by dividing the number by 1000 using modulo operator %.

Here is an example:

int price = 421039;lastThreeDigits = price % 1000;System.out.println(lastThreeDigits);

References

Hope this code and post will helped you for implement Get the last 3 digits of a number in Java. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US