0

The following code is from my simplex JSON decoder

private Number decodeNumber() {
    int start = pos;
    boolean integer = true;
    while (buffer[pos++] != ',') {
        if (pos == buffer.length) {
            break;
        }
        if (buffer[pos] == '.') {
            integer = false;
        }
    }
    pos--;
    final String value = new String(buffer, start, pos - start);
    Number number;
    if (integer) {
        try {
            number = Integer.parseInt(value);
        } catch (final NumberFormatException e) {
            number = Long.parseLong(value);
        }
    } else {
        try {
            number = Float.parseFloat(value);
        } catch (final NumberFormatException e) {
            number = Double.parseDouble(value);
        }
    }
    return number;
}

It seems quite tedious deciding the type of the number but I can't think of a better way of doing so. Are there any alternatives other than looking for a decimal in the value/throwing exceptions?

1
  • Please post a sample buffer input string. Jan 20, 2015 at 3:30

2 Answers 2

0

You can use the parse method of NumberFormat:

NumberFormat.getInstance().parse(value);
0

Get rid of the initial scan, and then just try Integer.parseInt(), Float.parseFloat() and Double.parseDouble(), in that order, until you don't get a NumberFormatException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.