2013-01-22 63 views
-4

正在编写一个android代码,其中的文本视图正由我的java类中的计算%填充。Android:使用INTEGER填充TextView

因为我不得不计算%,所以我的最终变量(calcPerc)是一个双重类型的变量。它不会将TextText放入我的TextView中。 请帮忙。

代码

int totDiff = (totalMA - totalIA); 
    double beforeperc = ((double)totDiff/(double)totalIA); 
    calPerc = ((double)beforeperc*100); 

    percentage = (TextView)findViewById(R.id.populatePercentage); 
    percentage.setText(calPerc); 

我得到的错误是

在类型的TextView的方法的setText(CharSequence的)不适用于参数(双)

而且,还有一个后续问题。变量“calPerc”,因为它是double,所以在小数点后面给我无限数字。我如何将它舍入到2位小数?

+0

使用Integer.toString(calPerc)在TextView中显示int值 –

+0

谢谢!这工作。你能告诉我如何限制小数只有2? – Jasma

+0

简单的谷歌搜索会让你回答。你必须使用String.Value Of或者只使用上面提到的Krishna。论坛鼓励寻找现有的答案。 – VendettaDroid

回答

2

这应该为当前语言环境正确格式化显示的值(最多2个小数);

NumberFormat twoDecimals = NumberFormat.getInstance(); 
twoDecimals.setMaximumFractionDigits(2); 
percentage.setText(twoDecimals.format(calPerc)); 
+0

感谢您回答任何讽刺意见。我对Android很陌生,这有所帮助。 – Jasma

+0

@Jasma很高兴能有所帮助:) –

0

为了能够更好地控制格式(如小数点后限制的位数),你可以使用String.format()

percentage.setText(String.format("%.2f %%", calPerc)); 

be wary of the default locale

+0

谢谢!这工作。你能告诉我如何限制小数只有2? – Jasma