So the question is very simple.
How to check in java if first digit of an int
is 0
;
Say I have:
int y = 0123;
int n = 123;
Now I need an if statement that would return true for y
and false for n
.
So the question is very simple.
How to check in java if first digit of an int
is 0
;
Say I have:
int y = 0123;
int n = 123;
Now I need an if statement that would return true for y
and false for n
.
Your question is pretty strange for one reason: An int value cannot start by 0. But if you store your value in a String, you could check it easily like this:
public static void main(String[] args) {
String y = "0123";
String n = "123";
System.out.println(startByZero(y));
System.out.println(startByZero(n));
}
public static boolean startByZero(String value) {
return value.startsWith("0");
}
Output:
true
false
EDIT: Like Oleksandr suggest, you can use also:
public static boolean startByZero(String value) {
return value.charAt(0) == '0';
}
This solution is more efficient than the first. (but at my own opinion it's also less readable)
Your
y = 0123
will be considered as octal base but
n = 123
is an decimal base.
Now when you do
if (y == n )
the numbers will be compared based on decimal base always.
You'll have to do conversions from octal to decimal or vice-versa based on your requirements.
You could also use Strings
as @Valentin recommeneded.
This doesn't seems on topic but based on OP's comment :
The reason I need this is because I'm working with self made dates. And in case I have a date '03.04.2018' I want to print it as 3. 4. 2018, without the 0s in the beginning.
Lommmp
If you don't want to reinvent the wheel, you should use java time API to parse and format your dates :
LocalDate date = LocalDate.parse("03.04.2018", DateTimeFormatter.ofPattern("MM.dd.yyyy"));
System.out.println(date.format(DateTimeFormatter.ofPattern("M.d.yyyy")));
3.4.2018
String.format("%01d",number);
for Zero padding with length 1.
like 0123
Read from: https://www.geeksforgeeks.org/java-string-format-examples/