在Android中将字符串转换为双精度浮点数

31

尝试从EditText获取double值并在将其传递给另一个Intent之前对其进行操作。不使用原始数据类型,以便可以使用toString方法。

问题是当我包含protein = Double.valueOf(p).doubleValue();样式命令时,程序立即关闭,logcat中没有任何信息。如果我注释掉它们并设置一些虚拟数据,如protein = 1.0;,它可以正常工作。 使用原始数据类型和解析double也会发生同样的情况。这段代码在普通java中使用虚拟数据可以正常工作。 我做错了什么?

EditText txtProt, txtCarb, txtFat, txtFiber, txtPoints;
String p, c, f, fi;
Double protein, carbs, fat, fiber;
double temp;
Integer points;

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Log.v("Create Prompt", "ready for layout");
     setContentView(R.layout.main);
     Log.v("Layout Created", "ready for variable assignment");
     txtProt = (EditText) findViewById(R.id.Protein);
     txtCarb = (EditText) findViewById(R.id.Carbs);
     txtFat = (EditText) findViewById(R.id.Fat);
     txtFiber = (EditText) findViewById(R.id.Fiber);
     txtPoints = (EditText) findViewById(R.id.Points);
     btnCalc = (Button) findViewById(R.id.Calc);
     Log.v("Variables Assigned", "ready for double assignment");

     p = txtProt.getText().toString();
     c = txtCarb.getText().toString();
     f = txtFat.getText().toString();
     fi = txtFiber.getText().toString();


     protein=Double.valueOf(p).doubleValue();
     carbs=Double.valueOf(c).doubleValue();
     fat=Double.valueOf(f).doubleValue();
     fiber=Double.valueOf(fi).doubleValue();
     Log.v("Doubles parsed", "ready for calculations");
     //these are the problem statements

     protein = 1.0;
     carbs = 1.0;
     fat = 1.0;
     fiber = 1.0;

     protein *= 16;
     carbs *= 19;
     fat *= 45;
     fiber *= 14;

     temp = protein + carbs + fat - fiber;
     temp = temp/175;

     points = new Integer((int) temp);

从文档中--getText() 返回 TextView 显示的文本。http://developer.android.com/reference/android/widget/EditText.html#getText(),除非您使用不同的缓冲类型调用了 setText? - Idistic
1
对于 kotlin,您可以像这样使用 toDouble()val d = textString.toDouble() - Zohab Ali
9个回答

79

我会这样做:

try {
  txtProt = (EditText) findViewById(R.id.Protein); // Same
  p = txtProt.getText().toString(); // Same
  protein = Double.parseDouble(p); // Make use of autoboxing.  It's also easier to read.
} catch (NumberFormatException e) {
  // p did not contain a valid double
}

编辑:程序立即崩溃,没有在logcat中留下任何信息。

我不确定logcat输出中是否有信息,但强制关闭通常意味着有未捕获的异常,比如NumberFormatException。


3
对于 kotlin,你可以使用 toDouble() 来实现,像这样:val d = textString.toDouble() - Zohab Ali

27

尝试这个:

double d= Double.parseDouble(yourString);

这与 Double.valueOf( your String ) 相比如何? - Joshua Pinter
这会引发NumberFormatException,因为您没有将double自动装箱为Double。 - waheed shah

5

您似乎将Double对象赋值给本地的double值字段。这真的能编译通过吗?

Double.valueOf()创建一个Double对象,所以不需要使用.doubleValue()。

如果您想要本地的double字段,您需要将该字段定义为double,然后使用.doubleValue()。


是的,它可以编译。我正在使用Double而不是double,这样我就可以通过intent.putExtra(string,string)将结果传递给另一个活动。 - ProfCommie
1
@jkj:这被称为自动装箱,是Java的一个记录功能。(编辑:更确切地说,在您的评论中是自动拆箱) - Izkata

2

使用Double(String)构造函数怎么样?所以,

protein = new Double(p);

不知道为什么会有所不同,但或许值得一试。


此外,在这里你没有捕获 NumberFormatException -- 这可能会导致问题。建议也要捕获并记录它,以防万一。 - MikeTheReader
为什么不捕获NumberFormatException会导致程序在打开之前就强制关闭? - ProfCommie
protein = new Double(p); 这个方法不起作用,而且也无法让 protein=Double.valueOf(p.trim()); 正常工作。我还尝试了 protein=Double.parseDouble(p.trim()); 但是没有成功。 - ProfCommie
啊,我明白为什么在程序完成之前应该处理它了,我很好奇这是否会影响程序在启动时强制关闭。 - ProfCommie
我已经回答了自己的问题。我的xml布局将编辑文本字段的默认值设为“”。我在编辑文本字段中加入了0,并添加了try catch块。 - ProfCommie
显示剩余2条评论

2

我曾经也遇到过同样的问题,但是我刚刚发现:

  • 在Oncreate方法中解析EditText值会导致应用程序崩溃,因为当应用程序启动时,没有任何值可以解析,或者只有字母占位符。

我的代码:

package com.example.herodav.volumeapp;

import android.renderscript.Double2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    EditText height, length, depth;
    TextView volume;
    double h,l,d,vol;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        height = (EditText)findViewById(R.id.h);
        length = (EditText)findViewById(R.id.l);
        depth = (EditText)findViewById(R.id.d);
        volume = (TextView)findViewById(R.id.v);

        Button btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateVolume();
                volume.setText("Volume = " + String.valueOf(vol));
            }
        });
    }

    public void calculateVolume(){
        h = Double.parseDouble(height.getText().toString());
        l = Double.parseDouble(length.getText().toString());
        d = Double.parseDouble(depth.getText().toString());
        vol = h*l*d;
    }
}

I


2
我有一个类似的问题。 为了将EditText文本内容正确格式化为double值,我使用以下代码:
try {
        String eAm = etAmount.getText().toString();
        DecimalFormat dF = new DecimalFormat("0.00");
        Number num = dF.parse(eAm);
        mPayContext.amount = num.doubleValue();
    } catch (Exception e) {
        mPayContext.amount = 0.0d;
    }

这与当前手机语言设置无关,可以返回正确的双精度值。

希望对您有所帮助;


1
  kw=(EditText)findViewById(R.id.kw);
    btn=(Button)findViewById(R.id.btn);
    cost=(TextView )findViewById(R.id.cost);


            btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { cst =  Double.valueOf(kw.getText().toString());
            cst = cst*0.551;
            cost.setText(cst.toString());
        }
    });

0
String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

0
double d = Double.parseDouble(aString);

确保变量aString仅包含数字。它可能在开头有一个'+'或'-'符号。

我使用了一个带引号的字符串,结果出现了错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接