Android除法运算,保留小数

进行Android开发已经差不多2年多了,第一次写这个博客。
再开发中遇到int/int,我们希望保留小数点,那怎么办呢?
我写了个方法可以进行此操作。

 /**
     * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
     * 定精度,以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
package ymq.demo03; import android.app.Activity; import android.os.Bundle; import android.view.*; import android.widget.*; public class demo03 extends Activity { /** Called when the activity is first created. */ String str=""; EditText et; int c=0,flag=0; double b=0.0,g=0.0,f=0.0; View vi; public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, 1, 1, "退出"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub if(item.getItemId()==1){finish();} return super.onOptionsItemSelected(item); } //计算方法 public double calculater(){ switch(c){ case 0:f=g;break; case 1:f=b+g;break; case 2:f=b-g;break; case 3:f=b*g;break; case 4:f=b/g;break; } b=f; c=0; return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获得按键 final Button number[]=new Button[10]; final Button fuhao[]=new Button[11]; fuhao[0]=(Button)findViewById(R.id.button01); fuhao[1]=(Button)findViewById(R.id.button02); fuhao[2]=(Button)findViewById(R.id.button03); fuhao[3]=(Button)findViewById(R.id.button04); fuhao[4]=(Button)findViewById(R.id.button05); fuhao[5]=(Button)findViewById(R.id.button06); fuhao[6]=(Button)findViewById(R.id.buttonce); fuhao[7]=(Button)findViewById(R.id.buttonc); fuhao[8]=(Button)findViewById(R.id.zheng); fuhao[9]=(Button)findViewById(R.id.kaifang); fuhao[10]=(Button)findViewById(R.id.pingfang); number[0]=(Button)findViewById(R.id.button0); number[1]=(Button)findViewById(R.id.button1); number[2]=(Button)findViewById(R.id.button2); number[3]=(Button)findViewById(R.id.button3); number[4]=(Button)findViewById(R.id.button4); number[5]=(Button)findViewById(R.id.button5); number[6]=(Button)findViewById(R.id.button6); number[7]=(Butto
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值