Let's say I have following number:
36702514
I want to separate the above number into 3 parts, which is 36, 702, 514.
Below is the code that I tried:
int num = 36702514;
int num1 = num.substring(0, 2);
int num2 = num.substring(2, 3);
int num3 = num.substring(5, 3);
Am I writing correct?
List<String> myNumbers = Arrays.asList(
NumberFormat.getNumberInstance(Locale.US).format(36702514).split(","));
My solution builds a comma-separated String
of the input in US locale:
36,702,514
This String
is then split by the comma to give the desired three pieces in the original problem.
List<Integer> numbers = new ArrayList<>();
Integer n = null;
for (String numb : myNumbers)
{
try
{
n = new Integer(numb);
}
catch (NumberFormatException e)
{
System.out.println("Wrong number " + numb);
continue;
}
numbers.add(n);
}
System.out.println(numbers);
You need to use substring()
on a Java String
, not a primitive int
. Convert your number to a String
using String.valueOf()
:
int num = 36702514;
String numString = String.valueOf(num);
int num1 = Integer.parseInt(numString.substring(0, 2));
int num2 = Integer.parseInt(numString.substring(2, 5));
int num3 = Integer.parseInt(numString.substring(5, 8));
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