将BigDecimal转换为可在ViewText字段中显示的类型

时间:2012-06-02 00:29:00

标签: java android

清一色 我很难获取EditText的值并搞乱它以预先形成方程和任务,如舍入和乘法。我听说BigDecimal是一个很好的方法,但很难将变量变为可以变为BigDecimal变量的类型(View-> String-> Float-> BigDecimal)然后获取它们到可以输出的类型(BigDecimal->?)。 这是我的代码:

 public class TippingActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void calculateNumbers(View view) throws ParseException {
        // Bill
        EditText text = (EditText)findViewById(R.id.edit_bill);             
        String value;
        value = text.getText().toString();
        float bill = Float.parseFloat(value);       
        BigDecimal billbd;
        billbd = new BigDecimal(bill);


        //Tip
        EditText text2 = (EditText)findViewById(R.id.edit_tip);
        String value2;
        value2 = text2.getText().toString();    
        if(!value2.contains("."))
            value2 = "."+value2;
        float tip = Float.parseFloat(value2);
        BigDecimal tipbd;
        tipbd = new BigDecimal(tip);

        //People
        EditText text3 = (EditText)findViewById(R.id.edit_people);
        String value3;
        value3 = text3.getText().toString();
        float people = Float.parseFloat(value3);
        BigDecimal peoplebd;
        peoplebd = new BigDecimal(people);
        //Answer
        TextView answer = (TextView) findViewById(R.id.answer);
        //Answer to string
        String answerstring;
        answerstring = answer.getText().toString();
        //Answer to Float
        float answerfloat = Float.parseFloat(answerstring);
        //Answer to BigDecimal
        BigDecimal answerbig;
        answerbig = new BigDecimal(answerfloat);
        answerbig.setScale(2, RoundingMode.HALF_UP);
        answerbig = billbd.multiply(tipbd).add(billbd).divide(peoplebd);
        //Answer to String
        String answerfrombd = answerbig.getText().toString();        
        answer.setText(answerfrombd);       
    }
}

在底部的第二行代码中,我收到错误

`String answerfrombd = answerbig.getText().toString();`

因为我无法从BigDecimal转到String。有任何想法吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以根据自己的需要进行显示。

answerbig.toPlainString() 

或:

answerbig.toBigInteger().toString()