在法国机器上执行时java.lang.NumberFormatException

时间:2017-06-14 10:06:19

标签: java locale

在解析值时,在下面的代码中,我有时会遇到法国机器中的NumberFormat Exception。

double txPower;
DecimalFormat df = new DecimalFormat("##.##");

txPower = txPower + getDeltaP();
log.info("txpower value is -- "+txPower);
txPower = Double.parseDouble(df.format(txPower));


protected double getDeltaP() 
{
    return isNewChannelAddition ? apaConfig.deltaPadd : apaConfig.deltaPtune;
}

日志:

txpower value is -- -7.9
java.lang.NumberFormatException: For input string: "-7,9"

4 个答案:

答案 0 :(得分:3)

我建议使用为您的语言环境配置为默认值的小数点分隔符。

new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMA‌​T)).getDecimalSepara‌​tor();

答案 1 :(得分:1)

您必须解决问题:

一,您可以像这样使用replace(",", ".")

txPower = Double.parseDouble(df.format(txPower).replace(",", "."));

二,你可以使用本地DecimalFormat

DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
df.applyLocalizedPattern("##.##");
txPower = txPower + getDeltaP();
txPower = Double.parseDouble(df.format(txPower));

答案 2 :(得分:1)

您也可以拨打此类String.format("%.2f", -7.9)

答案 3 :(得分:0)

Double.parseDouble不支持特定于语言环境的小数点(请参阅文档here)。请尝试使用DecimalFormat来解析:

txPower = df.parse(df.format(txPower)).doubleValue();

话虽如此,我必须问你希望获得什么,将doubletxPower转换为String,将字符串解析为double并且将结果放回txPower