0

I want to parse a string to decimal using this method

 try {                
       Double.parseDouble(str);
    } catch (Exception exception) {
       exception.printStackTrace();                
    }

It throws exception if I put any letter in EditText or a number followed by a letter(so far so good),but when I enter a number followed by letter d or f(example 2.1or 2.1f) it doesen't throw exception.The method treats 2.1d string or 2.1f string as 2.1float or 2.1double and return the double as 2.1d or 2.1f and the program crashes. I also tried to parse the string using :

NumberFormat.getInstance().parse(str);

Double.valueOf(str);

 Double doubleObject = new Double(str);
 double number = doubleObject.doubleValue();

StringUtils.isNumeric(str);

and the result was the same.

In the end I did it using if(str.contains(d)||str.contains(f))throw new Exception(...)

Is there another method or another way to do this without using if.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
John
  • 17
  • 7

2 Answers2

0

I would do it this way if I were you.

Double numberVar = Double.parseDouble(yourEditText.getText().toString());

if(new Double(numberVar) istanceof Double){
    return true;
}

Very clean and just because a string contains a 0 or 1 or any other number does not mean it does not contain an a or an I.

Joshua Blevins
  • 689
  • 1
  • 10
  • 27
-2

You should use Long to parse a number. Because Double is a floating point number and it does not throw Exception for Floating value and also d represent the value in Double so still it will not throw Exception. You should use Long for this.

Like this

Long.parseLong(str);

but still it will accept l with the no. so then you can add an if condition before parsing

if(!str.contains("l"))
{
    Long.parseLong(str);
}
else
{
    // it is not a number.
}

another solution is that put inputType inside the EditText

android:inputType="numberDecimal"

Hope it will work for you.

Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40
  • "_example 2.1or 2.1f_" ... an you want to parse that in a Long ? – AxelH Mar 22 '18 at 08:20
  • If you want to check decimal number then do not use Long, double is good for that. but instead of this logic you should use inputType="numberDecimal". that will work surely. – Vishal Chhodwani Mar 22 '18 at 08:41