2013-10-01 40 views
0

我已经使用了十进制格式类来设置editText变量为我的格式变量mark1Format。但我不知道如何设置新的格式变量到这个我的意思是设置格式变量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+""); 
    } 
+0

我的头顶作品没有理由'的DecimalFormat(“# 。##“)'应该可以工作 –

+0

是的,但我不知道如何将editText结果设置为我的格式化结果..任何想法? – user2815899

+0

'result1.setText(df.format(mark1));' –

回答

0

该函数将返回只有尽可能多的小数点的双重只要你想......

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(); 
} 

享受 编辑

这对我来说完美的作品...尝试这样做: 首先不需要初始化result1和result2两次...一次就足够了... 其次尝试使用绑定来获得你的双打:

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

,然后你只需要调用

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

还有就是为什么它不应该工作......这个功能在我的程序

+0

谢谢,我将如何在我的代码中实现这个?我正在猜测'圆(mark1,2);'对吗? – user2815899

+0

你猜对了先生.... :) –

+0

那还没有工作,仍然得到约11位小数位。任何想法? – user2815899

相关问题