简体   繁体   English

当十进制为0时转换DecimalFormat.parse()的结果时,ClassCastException

[英]ClassCastException when casting result of DecimalFormat.parse() when decimal is 0

I'm using DecimalFormat to deal with number formats from different locales. 我正在使用DecimalFormat处理来自不同语言环境的数字格式。 My DecimalFormat variable is declared as follows: 我的DecimalFormat变量声明如下:

NumberFormat m_nf;
DecimalFormat m_df;

if (strCountry.equals("IT") || strCountry.equals("ES"))
    locale = java.util.Locale.ITALIAN;
else
    locale = java.util.Locale.ENGLISH;

m_nf = NumberFormat.getInstance(locale);

m_nf.setMaximumFractionDigits(1);

m_df = (DecimalFormat) m_nf;
m_df.applyPattern(".0");

I'm then obtaining a value from my method getLowerLimit() and formatting it as a string. 然后,我从方法getLowerLimit()获取一个值并将其格式化为字符串。 This could either be something like "2.1" (in US format) or "2,1" in Italian format. 可能是“ 2.1”(美国格式)或“ 2,1”(意大利格式)。 The value is then stored as a Double using DecimalFormat.parse() . 然后使用DecimalFormat.parse()将值存储为Double

try {
    String strValue = m_df.format(getLowerLimit());
    Double nValue = (Double) m_df.parse(strValue);
} catch (ParseException | ClassCastException e) {
    ErrorDialogGenerator.showErrorDialog(ExceptionConstants.LOWER_LIMIT, e);
    System.exit(1);
}

This code is working OK for me EXCEPT when the decimal of the number is 0. For example it works when the value is "2.1" but not when it is "2.0". 除了数字的十进制为0之外,这段代码对我来说还可以。例如,当值为“ 2.1”而不是“ 2.0”时,此代码有效。 That is when it throws the following exception: 那是当它抛出以下异常时:

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double

Why won't it work when the decimal is a 0? 十进制为0时为什么不起作用? How do I rectify this? 我该如何纠正? Thanks! 谢谢!

Since NumberFormat.parse() returns a Number , it can return any concrete Number implementation, such as Integer or Float , for example. 由于NumberFormat.parse()返回Number ,因此它可以返回任何具体的Number实现,例如IntegerFloat Casting it to Double you make an assumption that it will return Double , but it might prove wrong in many cases (as you've witnessed). 将其强制转换为Double您会假设它将返回Double ,但是在许多情况下(如您所见),它可能被证明是错误的。

If you wish to get result as Double , you should go with Number.doubleValue() as such: 如果希望将结果作为Double ,则应使用Number.doubleValue()这样:

Double nValue = m_df.parse(strValue).doubleValue();

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

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