-1

I created a simple android currency converter app where the user enters the value in euro and the converted price is displayed in other currencies. But how do I round up the numbers to the nearest 50 cent? so if 1 euro is equal to 1.3395 dollars how do I get the app to display 1.50 dollars?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText editEuro = (EditText) findViewById(R.id.editEuro);
        final EditText editAud = (EditText) findViewById(R.id.editAud);
        final EditText editCad = (EditText) findViewById(R.id.editCad);
        final EditText editNzd = (EditText) findViewById(R.id.editNzd);
        final EditText editGbp = (EditText) findViewById(R.id.editGbp);
        final EditText editUsd = (EditText) findViewById(R.id.editUsd);

        Button buttonConvert = (Button)findViewById(R.id.buttonConvert);

        buttonConvert.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                double euro = Double.valueOf( editEuro.getText().toString());

                double aud = euro *  1.4471 ;
                double cad = euro *  1.4635 ;
                double nzd = euro *  1.5835 ;
                double gbp = euro *  0.7965 ;
                double usd = euro *  1.3395 ;

                editAud.setText(String.valueOf(aud));
                editCad.setText(String.valueOf(cad));
                editNzd.setText(String.valueOf(nzd));
                editGbp.setText(String.valueOf(gbp));
                editUsd.setText(String.valueOf(usd));

            }
        });
    }
user2026041
  • 131
  • 2
  • 3
  • 11
  • You can check http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java. In fact rounding in programming is a common issue – istovatis Dec 17 '14 at 15:51
  • 1
    @istovatis Rounding to the nearest half is a little more complex though... – Duncan Jones Dec 17 '14 at 15:55

2 Answers2

3

There is code-snippet for such things.

double value = 1.3395; // your value
double roundTo = 0.5; // number that you round to

value = roundTo * Math.round(value / roundTo);
Volodymyr Baydalka
  • 3,635
  • 1
  • 12
  • 13
0

One way is to multiply your input by 2, round that to zero decimal places, and divide by 2.

If your rounding function returns an integral type, then take care not to divide by an integral literal else the division will take place in integer arithmetic and you'll lose any fraction. Multiplying the final result by 0.5 instead of dividing by 2 will circumvent this.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483