Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using DecimalFormat to parse / validate user input. Unfortunately it allows characters as a suffix while parsing.

Example code:

try {
  final NumberFormat numberFormat = new DecimalFormat();
  System.out.println(numberFormat.parse("12abc"));
  System.out.println(numberFormat.parse("abc12"));
} catch (final ParseException e) {
  System.out.println("parse exception");
}

Result:

12
parse exception

I would actually expect a parse exception for both of them. How can I tell DecimalFormat to not allow input like "12abc"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
409 views
Welcome To Ask or Share your Answers For Others

1 Answer

From the documentation of NumberFormat.parse:

Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

Here is an example that should give you an idea how to make sure the entire string is considered.

import java.text.*;

public class Test {
    public static void main(String[] args) {
        System.out.println(parseCompleteString("12"));
        System.out.println(parseCompleteString("12abc"));
        System.out.println(parseCompleteString("abc12"));
    }

    public static Number parseCompleteString(String input) {
        ParsePosition pp = new ParsePosition(0);
        NumberFormat numberFormat = new DecimalFormat();
        Number result = numberFormat.parse(input, pp);
        return pp.getIndex() == input.length() ? result : null;
    }
}

Output:

12
null
null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...