计算不工作百分比的代码

时间:2013-11-30 11:06:21

标签: android calculator

我不知道如何从价格获得结果以显示折扣后的价格!!

        // write the percentage
    final EditText editPrice = (EditText) findViewById(R.id.editPrice);
    // write the price
    final EditText ePercent = (EditText) findViewById(R.id.ePercent);
    // Hopefully to get the result
    final TextView result = (TextView) findViewById(R.id.viewResult);

    Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
    buttonConvert.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                double price = Double.valueOf(editPrice.getText()
                        .toString());
                // percent
                double per = (price / 100.0f) * ePercent;;

                result.setText(String.valueOf(per));

任何帮助! 谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个..

            // getting value from editPrice and parsing to double
            double price = Double.parseDouble(editPrice.getText().toString());

            // same like that getting value from ePercent and parsing to double
            double ePer = Double.parseDouble(ePercent.getText().toString());

            // percent
            double per = (price / 100.0f) * ePer;;

            result.setText(String.valueOf(per));
            // or
            result.setText(""+per);

答案 1 :(得分:0)

Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
            double price = Double.parseDouble(editPrice.getText()
                    .toString());
            // percent
            double ePercent = Double.parseDouble(ePercent.getText()
                    .toString());

            //if ePercent between 0 and 1
                double result = price * (1.0f - ePercent);
            //if ePercent between 0 and 100
                double result = price * ((100.0f - ePercent)/100.0f);

            result.setText(String.valueOf(result));
    }
}