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 aNumber
, it can return any concreteNumber
implementation, such asInteger
orFloat
, for example. Casting it toDouble
you make an assumption that it will returnDouble
, but it might prove wrong in many cases (as you've witnessed).If you wish to get result as
Double
, you should go withNumber.doubleValue()
as such: