Get the first digit of a number in Java
In this post we will give you information about Get the first digit of a number in Java. Hear we will give you detail about Get the first digit 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 first digit of a number in Java.
Get the first digit of a number
To get the first digit of a number, convert the number to a string and call the substring() method on it, by passing the 0, 1 as a arguments.
The substring() method returns the first character of a string then convert the result back to a number to get the first digit.
Here is an example:
int price = 429;String priceStr = Integer.toString(price);int firstDigit = Integer.parseInt(priceStr.substring(0,1));System.out.println(firstDigit);
Output:
4
In the example above, on the first step we have converted the number to string, so we can call a substring() method on it.
We have passed the 0, 1 as arguments to the substring() method, so the extraction starts at index 0 and ends before index 1.
Note: Strings are sequence of characters, where indexes are zero-based. The first character is in position 0, the second in 1, and so on.
References
Hope this code and post will helped you for implement Get the first digit 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
