简体   繁体   English

Java 10 NumberFormat无法以指数格式解析double

[英]Java 10 NumberFormat fails to parse a double in exponential format

I have recently upgraded from Java 8 to Java 10. I have come across a failing test using Java 10 which I am not sure how to handle. 我最近从Java 8升级到Java 10.我遇到了使用Java 10的失败测试,​​我不知道如何处理。 We have some code that is parses String representation of double values into double values using java.text.NumberFormat.getInstance() . 我们有一些代码使用java.text.NumberFormat.getInstance()解析double值的String表示形式为double值。 In the cases where the value is written in exponential form, the parsed value is incorrect when using Java 10. 在以指数形式写入值的情况下,使用Java 10时解析的值不正确。

Here's my JUnit test: 这是我的JUnit测试:

@Test
public void testMe() throws ParseException {
    String input = "2.0E-4";
    double output = NumberFormat.getInstance().parse(input).doubleValue();
    System.out.println(output);
}

When using Java 8, the double variable is correctly set to 0.0002: 使用Java 8时,double变量正确设置为0.0002:

Java 8 run的屏幕截图

When using Java 10, the double value is incorrectly set to 2.0: 使用Java 10时,double值被错误地设置为2.0:

Java 10 run的屏幕截图

Does anyone know if this is an intentional change on Java's part? 有谁知道这是否是Java的故意改变?


It seems like Double.valueOf() parses it correctly, though. 但是,似乎Double.valueOf()正确地解析它。

From JDK 9 onwards, the default locale data uses data derived from the Unicode Consortium's Common Locale Data Repository (CLDR). 从JDK 9开始,默认语言环境数据使用从Unicode Consortium的公共区域设置数据存储库(CLDR)派生的数据。 So there are changes with respect to some locales in Java 9 and later. 因此,Java 9及更高版本中的某些语言环境有所变化。 Refer the release notes of Java 9 and the corresponding JEP 252 . 请参阅Java 9的发行说明和相应的JEP 252

Refer the exponential symbol at the CLDR number symbols chart, for en_AU the exponential symbol is e (lower case) rather than E (upper case). 请参考指数符号在CLDR数量的符号图,用于en_AU指数符号是e (小写),而不是E (大写)。 Hence, the difference in output. 因此,产出的差异。

String input = "2.0e-4";
double output = NumberFormat.getInstance().parse(input).doubleValue();
System.out.println(output);

will give the expected output : 将给出预期的输出:

java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
2.0E-4

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

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