如何使数字结果不带小数

How to make number result without decimal

我的代码有问题。我将复制简化代码,其中包含两个编辑文本和一个文本视图和按钮。 使用此代码,如果 editext1 中的值为“100”而其他 editext2 中的值为“60”,我得到的结果答案为“40.0”,它应该为“40”。谢谢

代码:

public class MainActivity extends AppCompatActivity {
    EditText number1;
    EditText number2;
    Button Add_button3;
    TextView descr;
    int ans=0;
    private BreakIterator view;

    @SuppressLint("CutPasteId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //
        number1=(EditText) findViewById(R.id.editText_first_no);
        number2=(EditText) findViewById(R.id.editText_second_no);
        Add_button3=(Button) findViewById(R.id.add_button3);
        descr = (TextView) findViewById(R.id.textView_DESC);

        //
        Add_button3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                double num1 = Double.parseDouble(number1.getText().toString());
                double num2 = Double.parseDouble(number2.getText().toString());
                double sump = num1 - num2;

                descr.setText(Double.toString(sump));
            }
        });
    }
}

有两个选项,转换和使用数学 class。

要投:descr.setText(Integer.toString((int)sump));

这种方法只有一个缺点,即您正在丢失信息。

因此,如果您抽象 double sump = 5.0 - 3.3; 等于:1.7000000000000002,则转换为您“1”。

在我看来更好的方法是使用 Math class 尤其是方法 random() 即:

descr.setText(Math.round(sump));

该方法也会删除一些数据,但会将数字四舍五入为最接近的整数(整数),这是处理类似情况的首选方法。

更多请查看:How to convert float to int with Java

像这样使用DecimalFormat

在科特林中

DecimalFormat("##.##").format(yourValue)

在Java中:

new DecimalFormat("##.##").format(yourValue);