by Sai gowtham

Get the last digit of a number in Java

In this tutorial, we are going to learn about how to get the last digit of a number in Java.

Get the last digit of a number

To get the last digit of a number, convert the number to a string and call the substring() method on it, by passing the last character index as a argument.

The substring() method returns the last character of a string then convert the result back to a number to get the last digit.

Note: string.length()-1 is the index of a last character.

Here is an example:

int price = 429;
String priceStr = Integer.toString(price);
int lastCharIndex = priceStr.length()-1; // last character index
int lastDigit = Integer.parseInt(priceStr.substring(lastCharIndex));
System.out.println(lastDigit);

Output:

9

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()-1 as argument to the substring() method, so it returns the last character.

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

Note: Strings are sequence of characters, where indexes are zero-based. The last character is in position 0, the second in 1, and so on.

References

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2022 (Beginner + Advanced)
JavaScript - The Complete Guide 2022 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY