我正在使用
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");
然后,我从我的方法中获得一个值
getLowerLimit()
并将其格式化为字符串。这可以是类似“2.1”(美国格式)或“2,1”(意大利格式)。然后将该值存储为
Double
使用
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);
}
该代码对我来说工作正常,除非数字的小数点为0。例如,它在值为“2.1”时工作,但在值为2.0时不工作。也就是说,它抛出以下异常:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
为什么当十进制数是0时它不工作?如何纠正这一点?谢谢