1

嗨,我想使 TextView 级别可以输出小数,但我不知道该怎么做,有人知道吗?现在它只输出 1,但我希望它输出 1.80。:)

public class Main extends Activity {

int counter;
EditText weight, hours;
TextView amount, level;
Button calcuate;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    counter = 0;
    weight = (EditText) findViewById(R.id.weight);
    hours = (EditText) findViewById(R.id.hours);
    amount = (TextView) findViewById(R.id.amount);
    level = (TextView) findViewById(R.id.alcohol_level);
    calcuate = (Button) findViewById(R.id.calcuate);


    final String widmark = getResources().getString(
            R.string.widmark);
    final String hundra = getResources().getString(
            R.string.hundra);
    final String cl = getResources().getString(
            R.string.cl);

    calcuate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Integer wid, mgs;

            String w = weight.getText().toString();
            String h = hours.getText().toString();

            wid = Integer.parseInt(w) * Integer.parseInt(widmark) / Integer.parseInt(hundra);
            mgs = Integer.parseInt(cl) / Integer.parseInt(wid.toString()) / Integer.parseInt(hundra);

            level.setText(mgs.toString());
        }
    });

}

}
4

2 回答 2

1

您的mgs变量是一个 Integer 对象。将其设置为浮点型以显示小数位。

float mgs = Integer.parseInt(cl) / Integer.parseInt(wid.toString()) / Integer.parseInt(hundra);

我希望这有帮助。

于 2012-08-12T16:13:05.070 回答
0

int除法只会产生int's。如果你希望你的输出是floatdouble类型,你必须使用doublefloat除法。

Double mgs;

mgs = Double.parseDouble(cl) / Double.parseDouble(wid.toString()) / Double.parseDouble(hundra);

请注意,并非表达式中考虑的所有变量都必须是double',只有其中一个需要。

这里值得注意的另一件事是您是否需要两位小数(假设这里是货币)。默认情况下,Java/Android 只会根据需要输出尽可能多的小数位。 1.80将显示为1.8。为了缓解这种情况,您应该使用 a NumberFormat(特别是使用NumberFormat.getCurrencyInstance()),以便您可以指定您想要默认Locale货币的小数位数。

于 2012-08-12T16:13:34.057 回答