将String转换为Double时无效

时间:2013-05-08 06:49:30

标签: android double number-formatting separator

我得到一个NumberFormatException:在这行代码中无效的双“111,000,000”:

double SalePotential = Double.valueOf(EtPotential.getText().toString());

在开始时我使用了Numberformat,格式化我的double值以分隔数字并将其插入EditText但是当我尝试检索EditText的值时它会抛出异常:

NumberFormat f = NumberFormat.getInstance();
EtPotential.setText(String.valueOf(f.format(PTData.SalePotential)));

我也尝试过DecimalFormat或Double.parseDouble而没有成功。任何帮助,将不胜感激! :

DecimalFormat f = new DecimalFormat("###.###", DecimalFormatSymbols.getInstance());
double SalePotential = Double.parseDouble(EtPotential.getText().toString());

2 个答案:

答案 0 :(得分:6)

在解析之前删除“,”

double SalePotential = Double.parseDouble(EtPotential.getText().toString().replace(",", ""));

更新:正确实施

double salePotential = 0; // Variable name should start with small letter 
try {
    salePotential = Double.parseDouble(EtPotential.getText().toString().replace(",", ""));
} catch (NumberFormatException e) {
    // EditText EtPotential does not contain a valid double
}

快乐编码:)

答案 1 :(得分:1)

使用替换功能替换所有出现的,

     String  s= EtPotential.getText().toString();
     s = s.replace(",", ""); 
     try
     {
       double SalePotential = Double.parseDouble(s);
     }catch(NumberFormatException e)
     {
         e.printStackTrace();
     }