0

I would like to check whether the string is able to convert to float or int.

For example:

I received

temp = 36.50 

This value can be converted into float using

float Temp = Float.parseFloat(temp);

But what if I received

temp = 36.#0

My app will crash. So how can I check whether the string I received is able to convert to float?

Also for Int how do I do that?

Darwin von Corax
  • 5,201
  • 3
  • 17
  • 28
Spotty
  • 197
  • 2
  • 2
  • 14
  • 4
    Well, use a `try-catch` block. Or if you hate exceptions, try a regex to check whether input string is a valid float value – TheLostMind Apr 14 '16 at 06:18
  • try parsing using both `parseInt` and `parseFloat` in a try-catch block with `parseFloat` first. Whenever you successfully parse one, store a boolean value. In the end, read the boolean value to check. – Ian Apr 14 '16 at 06:22
  • Also note that even `36.0` can fail to parse depending on the local language – SomeJavaGuy Apr 14 '16 at 06:24
  • Have a look at this question and it's accepted answer: http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java – camelCaseCoder Apr 14 '16 at 06:24

2 Answers2

7

try this

float temp = 0 ;
    try {
    temp = Float.parseFloat(temp);
    } catch (NumberFormatException ex) {
    // Not a float    
    }     
 /*
    you can do something with temp variables in here
 */
crashOveride
  • 839
  • 6
  • 12
0

You can determine if String is Integer or not then convert it to avoid crashes or try-catch.

Please check this link to learn how

Determine if a String is an Integer in Java

Community
  • 1
  • 1
Ahmed M. Abed
  • 599
  • 3
  • 9
  • 22