While there are many rounding questions answered in StackO., I could not quite translate this to my multi-part question. (I am not sure why the link at the top of my post says "answer is here"... because this feels more like a resource to me, one that, for a beginner, is very difficult to sift through. I would not have come up with the answer someone presented on my post, just by looking through all of that conversation and analyzing the link for RoundingMode on that page. I see part of the right code is there, but only after it has been pointed out to me by someone who knew the answer.)
1. I need to round my finalBill TextView field so that it is to 2 decimal places. I heard using BigDecimal is good, but don't know how to write it, or where to put it in my code (I am a beginner).
2. Would it be more wise to round the double variable (within my onClick methods), before I convert to a String? Or would it be better to round the final answer that is delivered in a String (in the finalBill TextView field)?
Right now, I get the final answer that has many, many decimals behind it. I just need 2.
Backstory: I am creating a tip calculator, and when the onClick method executes for each button (10%, 15%, and 20%)... this should calculate the new total bill that includes tip, and also give the numeric answer (which has already been converted to a TextView) in a number no more than 2 decimal points. Thanks for your help!
Here is my code: I only included the amount including the first method onTen, since this method is where the tip is calculated and where the rounding needs to happen. (Other buttons not included for simplicity sake).
package com.example.nonitips;
import java.math.BigDecimal;
import java.math.RoundingMode;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText originalBill;
private double billWithTip;
String billString;
private TextView finalBill;
private Button btnTen;
private Button btnFifteen;
private Button btnTwenty;
double rounder = billWithTip;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
originalBill = (EditText)findViewById(R.id.originalBill);
}
public void onTen (View v) {
//Toast.makeText(this, "Tipping at 10%", Toast.LENGTH_SHORT).show();
btnTen = (Button)findViewById(R.id.btnTen);
//The button gets the setOnClickListener
btnTen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double bill = Double.parseDouble(originalBill.getText().toString());
billWithTip = bill * 1.10;
//Turns the answer back into a string
String billString = String.valueOf(billWithTip);
finalBill = (TextView)findViewById(R.id.finalBill);
finalBill.setText(billString);
}
});
}
}