PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

[FIXED] How to make number result without decimal

 August 11, 2022     android, decimal, java, numbers, rounding     No comments   

Issue

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));
            }
        });
    }
}

Solution

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



Answered By - Konrad
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing