skip to Main Content

I’m taking an EditText input from user like "1/3","1/4" etc. This input must be converted to Double.

This is what I’m trying to do with the code:

double shareDouble= Double.parseDouble(etShare.getText().toString());

But this throws a NumberFormatException. What I’m doing wrong. Please help..

2

Answers


  1. Split the string

    val s = "1/4"
    val splitString = s.split("/")
    val top = splitString[0].toDouble()
    val bottom = splitString[1].toDouble()
        
    val number = top / bottom
    
    Login or Signup to reply.
  2. Check below function

        private double convertFractionToDouble(String fraction) throws Exception {
            String[] parts = fraction.split("/");
            if (parts.length != 2) {
                throw new Exception("Invalid fraction format");
            }
            int numerator = Integer.parseInt(parts[0]);
            int denominator = Integer.parseInt(parts[1]);
            return (double) numerator / denominator;
        }
    

    You have to split string to index 0 and index 1.


    And call it in your code like :

            EditText editTextFraction = findViewById(R.id.editTextFraction);
            Button buttonConvert = findViewById(R.id.buttonConvert);
            TextView textViewResult = findViewById(R.id.textViewResult);
    
            buttonConvert.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String fraction = editTextFraction.getText().toString().trim();
    
                    if (fraction.isEmpty()) {
                        Toast.makeText(MainActivity.this, "Please enter a fraction", Toast.LENGTH_SHORT).show();
                        return;
                    }
    
                    try {
                        double result = convertFractionToDouble(fraction);
                        textViewResult.setText(String.valueOf(result));
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "Invalid fraction format", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search