Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - separate number into 3 parts

Tags:

java

int

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?

like image 465
KKL Michael Avatar asked Jul 16 '15 06:07

KKL Michael


2 Answers

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);
like image 99
Developer Marius Žilėnas Avatar answered Oct 18 '22 02:10

Developer Marius Žilėnas


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));
like image 5
Tim Biegeleisen Avatar answered Oct 18 '22 03:10

Tim Biegeleisen