计算百分比并在textview android studio中显示

问题描述 投票:0回答:1

我正在开发一个应用程序,我将1个变量int通过一个活动字符串传递给下一个活动,在下一个活动中我接受该字符串并再次返回它并返回一个int,然后我计算一个百分比并显示和一个textview,过去变量和大约1所以我检查它是否为空,然后我计算百分比ex:((3/45)* 100)并在文本视图中显示,再次查看字符串...但无论如何我犯了一个错误什么可以?

    Bundle bundle = getIntent (). GetExtras ();
    String aprox1 = bundle.getString ("aprox1");
    if (aprox1! = null)
    try {
    num3 = Integer.parseInt (aprox1);
    result = Math.round ((num3 / 45) * 100);
    TextView counter2 = (TextView) findViewById(R.id.textView16);
    String abcString2 = Integer.toString (result);
    counter2.setText (abcString2);
    }
    catch (NumberFormatException e) { 
    }
android android-studio math textview calc
1个回答
1
投票

你需要在if语句之后加{},如下所示:

  if (aprox1! = null) {
    try {
    num3 = Integer.parseInt (aprox1);
    result = Math.round ((num3 / 45) * 100);
    TextView counter2 = (TextView) findViewById(R.id.textView16);
    String abcString2 = Integer.toString (result);
    counter2.setText (abcString2);
    }
    catch (NumberFormatException e) { 
    }
}

还值得注意的是,因为当你将它除以45时,num3是一个整数,你将获得一个整数而不是一个百分比。

要解决此问题,请在计算除法之前将num3设为double或将num3或45转换为double。

例如,一个简单的修复方法包括将第4行更改为以下内容:

result = Math.round ((num3 / 45.0) * 100);
© www.soinside.com 2019 - 2024. All rights reserved.