本文介绍了如何解析比NumberFormat在Java中更严格的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在验证表单中的用户输入。
I'm validating user input from a form.
我用,但它很邪恶,几乎可以允许任何内容。有没有办法解析数字更严格?
I parse the input with NumberFormat
, but it is evil and allow almost anything. Is there any way to parse number more strict?
例如。我想不允许这三个输入,对于一个整数,但 Numberformat
允许所有这些:
E.g. I would like to not allow these three inputs, for an integer, but Numberformat
allow all of them:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setParseIntegerOnly(true);
Number numberA = nf.parse("99.731"); // 99 (not what the user expect)
Number numberB = nf.parse("99s.231"); // 99 (invalid)
Number numberC = nf.parse("9g9"); // 9 (invalid)
System.out.println(numberA.toString());
System.out.println(numberB.toString());
System.out.println(numberC.toString());
推荐答案
也许这会有所帮助:
String value = "number_to_be_parsed".trim();
NumberFormat formatter = NumberFormat.getNumberInstance();
ParsePosition pos = new ParsePosition(0);
Number parsed = formatter.parse(value, pos);
if (pos.getIndex() != value.length() || pos.getErrorIndex() != -1) {
throw new RuntimeException("my error description");
}
(感谢)
这篇关于如何解析比NumberFormat在Java中更严格的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!