1

I have problem with code. I will copy simplified code, with two editext and one textview and button. With this code if value in editext1 is "100" and other editext2 is"60" I get result answer "40.0" and it should be "40". Thanks

for code:

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));
            }
        });
    }
}
Shankha057
  • 1,296
  • 1
  • 20
  • 38
Namma
  • 21
  • 4
  • 1
    Yes, that's normal behavior considering that you are using a `Double` to get the value. And in your example you have provided the input values as `Integer` ones. So everything is fine as it should work. – Shankha057 Oct 23 '19 at 23:29
  • 1
    Unclear from your question as to whether you should only accept `Integer` values or not. The answer will be different based upon this. – Scary Wombat Oct 24 '19 at 00:43

2 Answers2

1

There are two options, casting and using Math class.

To cast: descr.setText(Integer.toString((int)sump));

That approach has only one downside, you are losing information.

So if you abstract double sump = 5.0 - 3.3; which equals: 1.7000000000000002 the casting gives you '1'.

In my opinion better way is to use Math class and in particular method random() that is:

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

The method also will remove some data but it will round the number to the closest whole number (integer) which is a preferred way to deal with similar situations.

For more please check: How to convert float to int with Java

Konrad
  • 62
  • 5
  • Ok, work excellent with cast, I get some error with Math class, so I use cast, it is good for this one. – Namma Oct 24 '19 at 08:05
  • Hey, I'm glad that I can help. With Math class please change it to String as setText do not accept int: \descr.setText(Math.round(sump).toString()); – Konrad Oct 24 '19 at 10:02
0

Use DecimalFormat like this:

In Kotlin

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

In Java:

new DecimalFormat("##.##").format(yourValue);
Suraj Vaishnav
  • 7,777
  • 4
  • 43
  • 46