Get first digits of a number in Java

Asked

Viewed 3,910 times

-1

How do I take part of an integer number in Java? For example, I have a variable int a = 12345678, and the user wants to receive only 4 digits.

  • 1

    And what should the 4 digits be? This doesn’t seem to make much sense but at least it should have a criterion.

  • Indifferent, but to supplement the question, let us assume that they are always the first, that is, going from left to right. In this case with 4 digits the system would return me only 1234

  • 1

    Have you ever thought of turning into String, taking the digits you want and then saving into a new integer?

  • maybe a % 10000 ?

  • @Jjoathe problem with your method is that if the user asks only 2 digits, I will have to change the value of 10000.

  • It cannot be indifferent, there has to be a criterion. And your question speaks in 4 digits, now you say it can be an indeterminate number.

  • @Bigown sorry, is an indeterminate number informed by the user.

  • 1

    @Danlucioprada Just out of curiosity (since the problem seems very strange to me too), if you want to vary the number of digits just do a % (int)Math.pow(10, ndigitos). This takes the digits on the right, however (to get the ones on the left still has the problem - how many digits does the number have? Always 8? And if you have less, how does it look?)

  • 1

    @mgibsonbr I have found a mathematical solution p/ this. it is not perfect but solves most cases. If he needs something robust (this seems to be just a puzzle/exercise) of course he will have to think of another solution.

Show 4 more comments

2 answers

6


There are several ways to do this. One of them is to turn into string with valueOf() and take a piece of it with the method substr() and then convert back to int, thus:

import java.lang.*;

class Program {
    public static void main (String[] args) {
        System.out.println(PegaPrimirosDigitos(12345678, 4));
        System.out.println(PegaPrimirosDigitos(-12345678, 4));
        System.out.println(PegaPrimirosDigitos(123, 4));
        System.out.println(PegaPrimirosDigitos(-12, 4));
        System.out.println(PegaPrimirosDigitos(0, 0));
    }
    public static int PegaPrimirosDigitos(int valor, int digitos) {
        digitos = Math.max(1, digitos);
        int positivo = Math.abs(valor);
        String texto = String.valueOf(positivo);
        if(digitos > texto.length()) {
            return valor;
        }
        return Integer.parseInt(texto.substring(0, digitos)) * Integer.signum(valor);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Can also be done mathematically without involving conversions but really you don’t know how to do it?

import java.lang.*;

class Ideone {
    public static void main (String[] args) throws java.lang.Exception {
        System.out.println(PegaPrimirosDigitos(12345678, 4));
        System.out.println(PegaPrimirosDigitos(-12345678, 4));
        System.out.println(PegaPrimirosDigitos(123, 4));
        System.out.println(PegaPrimirosDigitos(-12, 4));
        System.out.println(PegaPrimirosDigitos(0, 0));
    }
    public static int PegaPrimirosDigitos(int valor, int digitos) {
        digitos = Math.max(1, digitos);
        int positivo = Math.abs(valor);
        int tamanho = (int)(Math.log10(positivo) + 1);
        if(digitos > tamanho) {
            return valor;
        }
        return valor / (int)Math.pow(10, tamanho - digitos);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I do not guarantee that it will work in all situations, but the central point of the solution is there. For lack of a better criterion definition I chose that at least should pick 1 digit. I also understood that the negative sign should be considered but it is not a digit.

This problem appears to be artificial and serves no real purpose but the solution is there. If you have more details, I may be able to give a better solution. The solution here is already better than defined in the question.

  • When we use negative numbers, your second @bigown solution returns the negative digit instead of the number itself.. see: http://ideone.com/z2yf8z that’s correct?

  • 2

    @Samueldiogo Yes, the requirement of the question does not ask for anything better than this. If the question had a more realistic and well-defined requirement, I would certainly seek another solution. Probably a more complicated solution, but for something like this you could even do some simple gambiarra p/ how to kill the signal, if necessary, calculate and then put the signal back if necessary.

  • 1

    @Samueldiogo I improved now, but maybe it got worse, someone who had voted in the answer before now thinks she’s worse and took the vote. There’s a funny thing that happens here.

4

At first, you can convert the number to a String and then use the method substring to "cut" from index 0 to the digit numbers that must be returned. For example:

public int foo(int number, int digits){
   String str = Integer.toString(number);
   if(digits> str.length())
       return number;

    boolean isNegative = str.startsWith("-"); 
    return Integer.valueOf(str.substring(0, isNegative ? digits + 1 : digits));
}

Example working on Ideone

  • Brow, its function is good, but does not work with negative numbers:http://ideone.com/xW4EgK

  • 1

    @Samueldiogo agree but the problem certainly does not require this kind of thing, there seems to be no requirement for this. If he had, he should have asked the question. Anyway it is possible to modify p/ meet this requirement. I just don’t do it in my answer because I know this won’t solve anything real. One or two abs() resolve the issue.

  • 1

    @Samueldiogo I am not able to test at the moment, but I edited my answer. Later I see more calmly.

  • Show Renan, it was just an observation :D but your edition contributed to a response beyond the scope and may help someone in the future! Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.