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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With