简体   繁体   中英

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

I'm using DecimalFormat to deal with number formats from different locales. My DecimalFormat variable is declared as follows:

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. This could either be something like "2.1" (in US format) or "2,1" in Italian format. The value is then stored as a Double using DecimalFormat.parse() .

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". 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? 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. 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).

If you wish to get result as Double , you should go with Number.doubleValue() as such:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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