java check how many digits in a number

java check how many digits in a number

To check how many digits are in a number in Java, you can convert the number to a string and then use the length method of the String class to determine the number of characters in the string.

For example, consider the following code:

‮refer‬ to:lautturi.com
int num = 12345;
String str = Integer.toString(num);  // str is "12345"
int digits = str.length();  // digits is 5

In this example, the Integer.toString method is used to convert the int value 12345 to a string, and the length method is used to count the number of characters in the string. The result is that the digits variable is assigned the value 5, which is the number of digits in the number.

You can also use this approach to check the number of digits in other types of numbers, such as long and double. For example:

long num = 1234567890L;
String str = Long.toString(num);  // str is "1234567890"
int digits = str.length();  // digits is 10

double num = 123.45;
String str = Double.toString(num);  // str is "123.45"
int digits = str.length();  // digits is 5

Note that this approach will count the number of characters in the string representation of the number, including any leading or trailing zeros or the decimal point. If you only want to count the digits before the decimal point, you can use the indexOf method

Created Time:2017-11-03 00:14:48  Author:lautturi