2011-07-06 21 views
12

使用的DecimalFormat使用这种号码的时候没有给出分析异常:DecimalFormat的转换数字与非数字

123hello

这显然不是一个真正的号码,并转换为123.0值。我怎样才能避免这种行为?

作为一个便笺hello123确实给出了一个例外,这是正确的。

感谢, 马塞尔

+0

看这个http://stackoverflow.com/questions/4324997/why-does-decimalformat-allow-characters-as-suffix –

回答

9

要做到准确的分析,您可以使用

public Number parse(String text, 
       ParsePosition pos) 

POS初始化为0,其完成时,它会给你已使用的最后一个字符之后的索引。

然后,您可以将其与字符串长度进行比较,以确保解析是准确的。

http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#parse%28java.lang.String,%20java.text.ParsePosition%29

+1

只有可怜的API不允许做这样的事情:decimalFormat.setStrict(true)(严格的意思是不允许123hello作为数字)。关键是你不能总是控制电话来解析你自己。其他库可能使用格式对象。非常感谢您的回复! – marcel

0

你可以验证它是数字使用正则表达式:

String input = "123hello"; 
double d = parseDouble(input); // Runtime Error 

public double parseDouble(String input, DecimalFormat format) throws NumberFormatException 
{ 
    if (input.equals("-") || input.equals("-.")) 
     throw NumberFormatException.forInputString(input); 
    if (!input.matches("\\-?[0-9]*(\\.[0-9]*)?")) 
     throw NumberFormatException.forInputString(input); 

    // From here, we are sure it is numeric. 
    return format.parse(intput, new ParsePosition(0)); 
} 
+2

您的代码不带Double.parseDouble(“123hello”)以外的任何内容。 DecimalFormat的要点是解析国际化的数字。 123 456,78是法语区域设置中的有效小数。 –

+0

@JB:的确,我想快点:D –

+0

感谢您的回复! – marcel

1

扩大对@ Kal的答案,这里是一个实用的方法,你可以用任何格式用做“严”解析(使用Apache公地StringUtils的):

public static Object parseStrict(Format fmt, String value) 
    throws ParseException 
{ 
    ParsePosition pos = new ParsePosition(0); 
    Object result = fmt.parseObject(value, pos); 
    if(pos.getIndex() < value.length()) { 
     // ignore trailing blanks 
     String trailing = value.substring(pos.getIndex()); 
     if(!StringUtils.isBlank(trailing)) { 
      throw new ParseException("Failed parsing '" + value + "' due to extra trailing character(s) '" + 
            trailing + "'", pos.getIndex()); 
     } 
    } 
    return result; 
} 
+0

感谢您的回复! – marcel