简体   繁体   English

如何将双精度变量格式化为两位小数?

[英]How to format double variables to two decimal places?

I have used the decimal format class to set the editText variables to my format variables mark1Format .But I'm not sure how to set the new format variables to this result1 = (EditText)findViewById(R.id.mark1); 我已经使用了十进制格式类将editText变量设置为我的格式变量mark1Format但是我不确定如何将新的格式变量设置为此结果result1 = (EditText)findViewById(R.id.mark1); I mean setting the format variables to the R.id.mark1Format.Anyone have a solution here? 我的意思是将格式变量设置为R.id.mark1Format。有人在这里有解决方案吗?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        result1 = (EditText)findViewById(R.id.mark1);
        result2 = (EditText)findViewById(R.id.mark2);


        Intent intent = getIntent();
        double mark1 = intent.getDoubleExtra("number1", 0);
        double mark2 = intent.getDoubleExtra("number2", 0);

      //format to two decimal places
        DecimalFormat df = new DecimalFormat("#.00");
        String mark1Format = df.format(mark1);
        String mark2Format = df.format(mark2);


        //set the variables on EditTexts like this :
        result1 = (EditText)findViewById(R.id.mark1);
        result2 = (EditText)findViewById(R.id.mark2);
        result1.setText(mark1+"");
        result2.setText(mark2+"");
    }

This function will return the double with only as many decimal points as you want... 此函数将返回只包含所需小数点的双精度数。

public static double round(double value, int places) {
   if (places < 0){
        return value;
   }
   BigDecimal bd = new BigDecimal(value);
   bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
   return bd.doubleValue();
}

enjoy EDIT 享受编辑

for me this works perfectly... try doing this: first of all no need to initialize result1 and result2 twice... one will suffice... secondly try to get your doubles using bundle like so: 对我来说,这是完美的...尝试这样做:首先不需要初始化result1和result2两次...一个就足够了...其次,尝试使用bundle来获得双打,如下所示:

Intent intent = new Intent();
intent = getIntent();
Bundle bundle = intent.getExtras(); 
mark1= bundle.getDouble("value");

and then you just call 然后你就打电话

result1.setText(round(mark1,2));

there is no reason why it shouldnt work... this function works in my programs 没有理由不起作用...此功能在我的程序中有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM