java - Why does DecimalFormat allow characters as suffix? -
i'm using decimalformat
parse / validate user input. unfortunately allows characters 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 expect parse exception both of them. how can tell decimalformat
not allow input "12abc"
?
from documentation of numberformat.parse
:
parses text beginning of given string produce number. the method may not use entire text of given string.
here an example should give idea how make sure entire string 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
Comments
Post a Comment