问题
In below code while parsing the value sometimes i am facing NumberFormat Exception in France machine.
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;
}
logs:
txpower value is -- -7.9
java.lang.NumberFormatException: For input string: "-7,9"
回答1:
I suggest to use the decimal separator configured as default for your locale.
new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMAT)).getDecimalSeparator();
回答2:
You have to ways to solve your problem :
One, you can use replace(",", ".")
like this :
txPower = Double.parseDouble(df.format(txPower).replace(",", "."));
Two, you can use the local for the DecimalFormat
:
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
df.applyLocalizedPattern("##.##");
txPower = txPower + getDeltaP();
txPower = Double.parseDouble(df.format(txPower));
回答3:
You can also call something like this String.format("%.2f", -7.9)
回答4:
Double.parseDouble
doesn't support locale-specific decimal points (see the doc here). Try using your DecimalFormat
to parse instead:
txPower = df.parse(df.format(txPower)).doubleValue();
Having said that, I must ask what you are hoping to gain by to turning the double
value txPower
into a String
, parsing the string into a double
and putting the result back into txPower
?
来源:https://stackoverflow.com/questions/44541638/java-lang-numberformatexception-while-executing-in-france-machine