0

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

  • 1
    https://stackoverflow.com/questions/343584/how-do-i-get-whole-and-fractional-parts-from-double-in-jsp-java – kelalaka Oct 10 '18 at 22:28
  • do you catch NumberFormatException? – kelalaka Oct 10 '18 at 22:30
  • Yea. It will crash here. `int a = Integer.parseInt(s_input);` If you want to take the approach of parsing the component parts out of the string, you need to separate them out ... by splitting the string before you parse. The `parseInt` method expects a valid integer as input. As the javadoc will confirm. (Hint: read it!!) The answer by @mikejonesguy is a better approach. – Stephen C Oct 10 '18 at 22:50

2 Answers2

1

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;
mikejonesguy
  • 9,779
  • 2
  • 35
  • 49
0
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];
                }
navylover
  • 12,383
  • 5
  • 28
  • 41