JAVA中数字格式异常,java – 无法解释数字格式中的异常

  • Post author:
  • Post category:java


我有这个功能:

static private DecimalFormat df1 = new DecimalFormat(“#0.###############”,

new DecimalFormatSymbols(Locale.US));

static private DecimalFormat df2 = new DecimalFormat(

“0.0##############E000”, new DecimalFormatSymbols(Locale.US));

public static String toChar(final double val) {

String cont = Double.toString(val);

final String f1 = df1.format(val);

final String f2 = df2.format(val);

try {

final double v1 = df1.parse(f1).doubleValue();

final double v2 = df2.parse(f2).doubleValue();

if (Math.abs(v1 – val) <= Math.abs(v2 – val) && f1.length() < 16) {

// 6.0 -> 6

cont = f1;

} else {

final int j = f2.indexOf(‘E’);

if (f2.charAt(j + 1) == ‘-‘) {

cont = f2.substring(0, j – 1) + “e” + f2.substring(j + 1);

} else {

cont = f2.substring(0, j – 1) + “e+” + f2.substring(j + 1);

}

}

} catch (final ParseException e) {

throw new AssertionError(e);

}

return cont;

}

现在,奇怪的事实是我们的一个客户能够从这段代码中获得异常:

java.lang.StringIndexOutOfBoundsException: String index out of range: -2

Begin trace of call stack:

Level 0: String.substring(..) {java.lang.String.java, -1}

Level 1: Functions.toChar(..) {….runtime.Functions.java, 1579}

行号1579指的是第二个子字符串是代码片段.如果变量f2中没有“E”,我可以得到这个结果,但我无法提供任何输入.

你有没有人看到我们在这里忽视的问题?