Abdirahman Mohamed
Abdirahman Mohamed

Reputation: 9

Separating double into integer and decimal parts in android studio

I am trying to separate decimal number into whole number and points in android studio

Button btSpilt;
EditText Input;
TextView wholenumber, points;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    wholenumber = (TextView) findViewById(R.id.wholenumber);
    points = (TextView) findViewById(R.id.points);
    Input = (EditText) findViewById(R.id.Input);
    btSpilt = (Button) findViewById(R.id.btSpilt);

    btSpilt = findViewById(R.id.btSpilt);
    btSpilt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String s_input = Input.getText().toString();

            double input = Double.parseDouble(s_input);
            int a = Integer.parseInt(s_input);
            double aa = a;
            double b = (10 * input - 10 * input)/10;

            String str_a = Integer.toString((int) aa);
            String str_b = Integer.toString((int) b);

            wholenumber.setText(str_a);
            points.setText(str_b);
        }
    });

it works well when input whole number but when input decimal the whole app crashes

Upvotes: 0

Views: 483

Answers (2)

navylover
navylover

Reputation: 13619

int a = Integer.parseInt(s_input);//this line caused error when s_input represents decimal.
double b = (10 * input - 10 * input)/10;//b always equal zero

to get whole and fractional parts of a double, you could try using split

                String s_input = Input.getText().toString();
                if (s_input.contains(".")) {
                    String[] split = s_input.split("\\.");
                    String whole = split[0];
                    String fractional = split[1];
                }

Upvotes: 0

mikejonesguy
mikejonesguy

Reputation: 10009

Math.floor() will help with this: https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#floor(double)

        double input = Double.parseDouble(s_input);
        double wholeNumber = Math.floor(input);
        double afterDecimal = input - wholeNumber;

Upvotes: 1

Related Questions