简体   繁体   English

如何解析比NumberFormat在Java中更严格的数字?

[英]How to parse numbers more strict than what NumberFormat does in Java?

I'm validating user input from a form. 我正在验证表单中的用户输入。

I parse the input with NumberFormat , but it is evil and allow almost anything. 我用NumberFormat解析输入,但它是邪恶的,几乎允许任何东西。 Is there any way to parse number more strict? 有没有办法解析数字更严格?

Eg I would like to not allow these three inputs, for an integer, but Numberformat allow all of them: 例如,我想不允许这三个输入,一个整数,但Numberformat允许所有这些:

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());

Maybe this helps: 也许这有助于:

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");
}

(Thanks to Strict number parsing at mynetgear.net ) (感谢mynetgear.net严格的数字解析

There are many ways to do that: 有很多方法可以做到这一点:

Integer.parseInt(String) will throw a NumberFormatException on all of your examples. Integer.parseInt(String)将在所有示例上抛出NumberFormatException。 I'm not sure if that's what you're looking for, but it's definitely "more strict." 我不确定这是不是你要找的东西,但它绝对是“更严格的”。

I wouldn't use java's number format routine, especially with the locale settings if you worry about validation. 如果您担心验证,我不会使用java的数字格式例程,特别是使用区域设置。

    Locale numberLocale = new Locale(“es”,”ES");
    NumberFormat nf = NumberFormat.getInstance(numberLocale);
    ParsePosition pos = new ParsePosition(0);
    Number test = nf.parse("0.2", pos);

You would expect there to be an issue here, but no.. test is equal to 2 and pos has an index of 3 and error index of -1. 你会期望这里有一个问题,但是没有..测试等于2而pos的索引为3,错误索引为-1。

I gave up on writing my own validation class, and went with NEBULA WIDGETS FormattedText 我放弃编写自己的验证类,并使用NEBULA WIDGETS FormattedText

It was written over the SWT widget API, but you can easily adapt the NumberFormatter class 它是通过SWT小部件API编写的,但您可以轻松地调整NumberFormatter类

将DecimalFormat与格式模式字符串一起使用。

Take a look at DecimalFormat that is a subclass of NumberFormat http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html 看一下DecimalFormat,它是NumberFormat的子类http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

DecimalFormat myFormatter = new DecimalFormat("###.###"); DecimalFormat myFormatter = new DecimalFormat(“###。###”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM