BoDiE2003
BoDiE2003

Reputation: 1359

Java: Split last digit from the rest of the INT

I have the next code, which gets a number, I need to split that number in to parts, firstPart should be the whole number without the last digit, and the secondPart should be only the last digit of the original number.

public Boolean verificationNumberFiscalId(String fiscalId) {

        // Trying to do a better wa yto do it
        Integer firstPart = fiscalId.length()-1;
        Integer secondPart = ??????????;



        // My old logic
        String NitValue = "";
        for (Integer i = 0; i < fiscalId.length()-1; i++) {
            NitValue = fiscalId.substring(i,1);
        }

        Integer actualValueLength = fiscalId.length()-1;        
        String digitoVerificador = fiscalId.substring(actualValueLength,1);
        return this.generateDigitoVerification(NitValue) == digitoVerificador;
    }
    /** 
     * @param nit
     * @return digitoVerificador
     * @comment: Does the math logic
     */
    public String generateDigitoVerification(String nit) {        
        Integer[] nums = { 3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71 };

        Integer sum = 0;

        String str = String.valueOf(nit);
        for (Integer i = str.length() - 1, j=0; i >= 0; i--, j++) {
            sum += Character.digit(str.charAt(i), 10) * nums[j];
        }

        Integer dv = (sum % 11) > 1 ? (11 - (sum % 11)) : (sum % 11);
        return dv.toString();
    }

Could you suggest me a better way to do it please? Thank you!

Upvotes: 3

Views: 19594

Answers (3)

austinbv
austinbv

Reputation: 9491

int x = 1343248724;
int firstpart = x/10;
int secondpart = x%10;

System.out.println(firstpart);
System.out.println(secondpart);

Mod (%) gives you the remainder which will be the last digit if you mod 10 Divide will drop the last digit. That way you don't have to actually search the string.

Doing all the length stuff seems a little like overkill to me

oh and to get your param as a int I would use

Interger.decode(fiscalId);

Upvotes: 16

darioo
darioo

Reputation: 47183

  1. Convert your number to a string. Use String.valueOf()
  2. Split that string into two strings. First, look at original string's length. For length n, use it's substring of (0,n-1) as the first new string. Use the last character (n) for the second string
  3. Use Integer.valueOf() to convert both strings back to integers.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298908

This is how you can get the Integers:

Integer firstPart = Integer.valueOf(
                        fiscalId.substring(0,fiscalId.length()-1));
Integer secondPart = Integer.valueOf(
                        fiscalId.substring(fiscalId.length()-1));

but I'd suggest getting ints instead:

int firstPart = Integer.parseInt(fiscalId.substring(0,fiscalId.length()-1));
int secondPart = Integer.parseInt(fiscalId.substring(fiscalId.length()-1));

Upvotes: 2

Related Questions