Android:使用INTEGER填充TextView

时间:2013-01-22 11:05:40

标签: android

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

由于我必须计算%,我的最终变量(calcPerc)是一个双重类型的变量。它不会将Text文件设置为我的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)不适用于参数(double)

此外,还有一个后续问题。变量“calPerc”因为它是double,在小数点后给出无限数字。我如何将它四舍五入为2位小数?

2 个答案:

答案 0 :(得分:2)

这应格式化当前区域设置的显示值(最多2位小数);

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

答案 1 :(得分:0)

要对格式进行更多控制(例如限制小数点后的位数),可以使用String.format()

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

但是be wary of the default locale