Detect if a string is numeric - doesn't work on iOS

16 views
Skip to first unread message

nickk...@gmail.com

unread,
Aug 6, 2017, 10:31:02 PM8/6/17
to CodenameOne Discussions
I need to tokenise a string (split by space) to see if it ends in a number or a word. I'm using this hack to do it:
    public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

On the simulator and android this returns false with a string such as "Room" on iOS it returns true.

Any other way of detecting if it is a number that is consistent across platforms?

Shai Almog

unread,
Aug 7, 2017, 2:05:04 AM8/7/17
to CodenameOne Discussions
That's probably something we need to fix (I suggest filing an issue) but I would suggest using a regular expression for this as relying on an exception for normal flow is problematic.

Dave Dyer

unread,
Aug 7, 2017, 1:12:12 PM8/7/17
to CodenameOne Discussions
It depends on your actual application, but I would recommend writing your own
filter to pass only tokens that are acceptable to you.  You shouldn't depend on
the arbitrary definition of "number".  Would "Infinity" be acceptable? parseDouble
thinks so.

nickk...@gmail.com

unread,
Aug 7, 2017, 7:30:44 PM8/7/17
to CodenameOne Discussions
I agree that using exceptions for normal flow isn't ideal but none of the regex I tried worked with the Codename One regex class properly. I've tried again and found a simple Regex did the job for my simplified use case. The number is generated by a count of user actions so is always an integer and will never get to infinity.

I guess it just shows that if there was an exception for other reasons the behaviour could be different on iOS compared to expected behaviour and it needs to be addressed.

Shai Almog

unread,
Aug 8, 2017, 1:11:51 AM8/8/17
to CodenameOne Discussions
It's possible the exception is thrown correctly for Integer. Floating point parsing is much harder.
Reply all
Reply to author
Forward
0 new messages