Reputation: 51
I want to split a 4-digit integer in to 2. i.e convert 1234
into two variables; x=12
and y=34
. Using Java.
Upvotes: 4
Views: 11264
Reputation: 351
In case you want to split the same no:
int number=1234;
int n,x,y; //(here n=1000,x=y=1)
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
If you want to split the number in (12*x,34*y){where x=multiple/factor of 12 & y=multiple/factor of 34),then
1234=f(x(12),y(34))=f(36,68)
int number=1234;
int n; //(here n=1000)
int x=3;
int y=2;
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
Upvotes: 1
Reputation: 18106
int a = 1234;
int x = a / 100;
int y = a % 100;
Upvotes: 3
Reputation: 1198
int four = 1234;
int first = four / 100;
int second = four % 100;
the first one works because integers are always rounded down, stripping the last two digits when divided by 100.
the second one is called modulo, dividing by 100 and then taking the rest. this strips all digits exept the first two.
Lets say you have a variable number of digits:
int a = 1234, int x = 2, int y = 2;
int lengthoffirstblock = x;
int lengthofsecondblock = y;
int lengthofnumber = (a ==0) ? 1 : (int)Math.log10(a) + 1;
//getting the digit-count from a without string-conversion
How can I count the digits in an integer without a string cast?
int first = a / Math.pow(10 , (lengthofnumber - lengthoffirstblock));
int second = a % Math.pow(10 , lengthofsecondblock);
and at the end something usefull if you have cases where the input could be negative:
Math.abs(a);
Upvotes: 4
Reputation: 1325
int num=1234;
String text=""+num;
String t1=text.substring(0, 2);
String t2=text.substring(2, 4);
int num1=Integer.valueOf(t1);
int num2=Integer.valueOf(t2);
System.out.println(num1+" "+num2);
Upvotes: -1
Reputation: 272287
You can treat it as a string and split it using substring(), or as an integer:
int s = 1234;
int x = s / 100;
int y = s % 100;
If it's originally an int, I'd keep it as an int and do the above.
Note that you need to consider what happens if your input is not four digit. e.g. 123.
Upvotes: 1