This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
For my simple calculator, I am showing the result in a TextView, but it is always showing decimals. How can I remove them ?
This is my code :
public class MainActivity extends Activity implements OnClickListener {
EditText etNum1;
EditText etNum2;
Button btnAdd;
Button btnSub;
Button btnMult;
Button btnDiv;
TextView tvResult;
String oper = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the elements
etNum1 = (EditText) findViewById(R.id.etNum1);
etNum2 = (EditText) findViewById(R.id.etNum2);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnSub = (Button) findViewById(R.id.btnSub);
btnMult = (Button) findViewById(R.id.btnMult);
btnDiv = (Button) findViewById(R.id.btnDiv);
tvResult = (TextView) findViewById(R.id.tvResult);
// set a listener
btnAdd.setOnClickListener((OnClickListener) this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double num1=0;
double num2=0;
double result=0;
// check if the fields are empty
if (TextUtils.isEmpty(etNum1.getText().toString())
|| TextUtils.isEmpty(etNum2.getText().toString())) {
return;
}
// read EditText and fill variables with numbers
num1 = Double.parseDouble(etNum1.getText().toString());
num2 = Double.parseDouble(etNum2.getText().toString());
// defines the button that has been clicked and performs the corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);
}
}
A non mathematical way to do it:
A short and simple method is, convert the double to string:
String text = String.valueOf(result);
Now you have the result in the string. Given that your requirement is that you don't want decimals, so split your string based on "." as a delimiter:
String str[] = text.split(".");
Now in str[0] you will have only the number part. so set it to the text view:
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + str[0]);
I'm sure this one works fine.
You can use DecimalFormat to format the result:
DecimalFormat df = new DecimalFormat("0.##########");
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + df.format(result));
This will print with up to 10 decimal places.
Many ways to do that, i use:
public static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
And then call:
round(yourAnswer, 2)
For BigDecimal:
http://developer.android.com/reference/java/math/BigDecimal.html
Efficient BigDecimal round Up and down to two decimals
Related
how can i match an iteration variable to the input variable in edit text, i wanted to create the armstrong number
it goes like this
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer one = Integer.parseInt(edt1.getText().toString());
Integer two = Integer.parseInt(edt2.getText().toString());
Integer three = Integer.parseInt(edt3.getText().toString());
Integer num1 = (one * one * one);
Integer num2 = (two * two * two);
Integer num3 = (three * three * three);
Integer sum = (num1 + num2 + num3);
tv2.setText(sum);
for (int i = 0; i < 5; i++) {
if (i==1){
(1 == 153)
}
}
}
});
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button check;
private TextView result;
private EditText input_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check =(Button) findViewById(R.id.button_check);
check.setOnClickListener(this);
result =(TextView)findViewById(R.id.result);
input_number =(EditText)findViewById(R.id.input_number);
}
#Override
public void onClick(View v) {
int num = Integer.parseInt(input_number.getText().toString());
int n = num;
int check =0,remainder;
while(num>0){
remainder = num % 10;
check = (int) (check + Math.pow(remainder,3));
num = num/10;
}
if(check == n)
result.setText(n+"is an Armstrong Number");
else
result.setText(n+"is not an Armstrong Number");
}
}
To confirm if user input is an armstrong number, you don't need to iterate. You simply need to compute sum of the cube of individual digits and confirm if it arithmetically equals the value of the figure of the digits when combine.
Your code will thus be refactored like below to solve the problem
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer one = Integer.parseInt(edt1.getText().toString());
Integer two = Integer.parseInt(edt2.getText().toString());
Integer three = Integer.parseInt(edt3.getText().toString());
// convert input text to three fields to one String
String joinedText = "" + one + two + three;
Integer num1 = (one * one * one);
Integer num2 = (two * two * two);
Integer num3 = (three * three * three);
Integer sum = (num1 + num2 + num3);
// you must setText as String
tv2.setText(Integer.toString(sum));
if(sum == Integer.parseInt(joinedText)){
// This is an armstrong number
}else {
// This is not an armstrong number
}
}
});
I am new to Android. I am creating a native MobilePOS Android application for printng by using Bluetooth. This is my code:
private void showandadd() {
/*String num="";
num=num+String.valueOf(number);*/
String string1="";
String string2="";
String string3="";
if(num==""){
Toast.makeText(this,"Wrong input!! try again", Toast.LENGTH_LONG).show();
}
if(flag==1) {
getItem(directadd);
if(blankflag!=1) {
int updatedPrice = Integer.parseInt(this.price);
int data = Integer.parseInt(this.num);
if(data==0){
Toast.makeText(this,"Wrong input!! insert different quantity number", Toast.LENGTH_LONG).show();
}else {
int d = updatedPrice * data;
this.price = d + "";
// String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add(num);
amount.add(price);
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}
}
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}else {
getItem(directadd);
if(blankflag!=1) {
//String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add("1");
amount.add(price);
num = "";
}
directadd="";
blankflag=0;
}
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
}
There are 3 strings assigned to result.
I am getting result twice when I am press second item.
when I am select first item getting "Itemname Quantity ampount" format like
Tea 1qty 10rs...when I enter second item output will came first item+first item+second item show like this:
Tea 1qty 10rs
Tea 1qty 10rs
Coffee 1qty 12rs
I want to get result
Tea 1qty 10rs
Coffee 1qty 12rs
like this...please any one can help me
A simple example would be to use one label and append to it each time you add a new item.
Instead of this:
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
Change it to this:
str = this.selection.getText().toString();
str += printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
this.selection.setText(str);
num="";
This question already has answers here:
java.lang.numberformatexception: invalid double: " "
(6 answers)
Closed 6 years ago.
I’m making an app that can compute all I needed with just 1 click of a button, but its forced closing when I'm pushing the “calculate” button, can anyone help me with what I did wrong?
previous = (EditText) findViewById(R.id.editText);
present = (EditText) findViewById(R.id.editText2);
Button calculate = (Button) findViewById(R.id.calculate);
consumption = (TextView) findViewById(R.id.textView1);
basic = (TextView) findViewById(R.id.textView2);
mmp = (TextView) findViewById(R.id.textView3);
stp = (TextView) findViewById(R.id.textView4);
before = (TextView) findViewById(R.id.textView5);
penalty = (TextView) findViewById(R.id.textView6);
after = (TextView) findViewById(R.id.textView7);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
makeCalculations();
}
});
}
private void makeCalculations() {
double n1 = Double.valueOf(previous.getText().toString());
double n2 = Double.valueOf(present.getText().toString());
double n3 = Double.valueOf(consumption.getText().toString());
double n4 = Double.valueOf(stp.getText().toString());
double n5 = Double.valueOf(mmp.getText().toString());
double n6 = Double.valueOf(penalty.getText().toString());
double n7 = Double.valueOf(before.getText().toString());
double n8 = Double.valueOf(basic.getText().toString());
consumption.setText("Your Consumption is: " + (n1 + n2));
basic.setText("Your Consumption is: " + (n3 * 280.00));
mmp.setText("Meter Maintenance Fee: " + 10.00);
stp.setText("Septage Fee: " + (n3 * 0.068) );
before.setText("On/Before Due Date: " + (n3 + n4 + n5));
penalty.setText("Penalty: " + (n3 / 10.00));
after.setText("After Due Date: " + (n6 + n7));
}
}
There is no validation. You should at least check that the string is not empty, but also maybe use a try catch in case a number is not entered. Then you could set the error text on the editText to explain that an invalid number was entered.
So you could do something like this for each double:
boolean answerOk = true;
double n1;
if (!previous.getText().toString().equals("") {
try {
n1 = Double.valueOf(previous.getText().toString());
} catch(NumberFormatException e) {
answerOk = false;
previous.setError("Invalid number");
}
} else {
answerOk = false;
previous.setError("Field is empty");
}
Only run the code at the bottom after all the double's are ok.
if (answerOk) {
// Do the other stuff here
}
I want to sum the numbers entered in two EditText then when the button is clicked I want the sum to be showed in the third EditText but it seems something is wrong.
This is my code:
result = (Button)findViewById(R.id.btn1);
nb1 = (EditText)findViewById(R.id.nb1);
nb2 = (EditText)findViewById(R.id.nb2);
nb3 = (EditText)findViewById(R.id.nb3);
}
public void result (View v){
String n1 = nb1.getText().toString();
int n11 = Integer.parseInt(n1);
String n2 = nb2.getText().toString();
int n22 = Integer.parseInt(n2);
nb3.setText(n11 + n22);
Use following code.
nb3.setText(String.valueOf(n11 + n22));
Change this
nb3.setText(n11 + n22);
to
nb3.setText(String.valueOf(n11 + n22));
Change:
nb3.setText(n11 + n22);
to
nb3.setText(String.valueOf(n11 + n22));
setText treats integers as a resource ID which is why you need to explicitly convert it to a string.
Do the following:
int num1 = Integer.parseInt(edit1.getText().toString());
int num2 = Integer.parseInt(edit2.getText().toString());
edit3.setText(String.valueOf(num1+num2));//this you need to do
Put:
nb3.setText("" + n11 + n22);
It will show NumberFormatException if you press the button without entering the value in the edittext. So do like this
public void result (View v){
try
{
int sum = 0;
String n1 = nb1.getText().toString();
int n11 = Integer.parseInt(n1);
String n2 = nb2.getText().toString();
int n22 = Integer.parseInt(n2);
sum = n11 + n22;
nb3.setText("Sum is = " + sum); // nb3.setText(" " + sum); if you don't want only result to be displayed.
}
catch (Exception e)
{
}
}
So currently I am making an educational application where users can view how to solve a given problem by pressing a button. While my code works fine initially, when I hit the back button and click my View Solution button, my default layout pops up and I cannot edit the last four TextViews. Here is my code:
public class AdditionTensSolutionActivity extends Activity {
public static ArrayList<TextView> explain = new ArrayList<TextView>(3);
public static Button nextstep;
public static int onesnum1 = TensAdditionExerciseActivity.n1display % 10;
public static int onesnum2 = TensAdditionExerciseActivity.n2display % 10;
public static int onesanswer = onesnum1 + onesnum2;
public static int onesanswermod = onesanswer % 10;
public static int tensnum1 = TensAdditionExerciseActivity.n1display / 10;
public static int tensnum2 = TensAdditionExerciseActivity.n2display / 10;
public static int tensanswer = tensnum1 + tensnum2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showsolutionlayout);
TextView numrow1 = (TextView) findViewById(R.id.solproblemrow1);
TextView numrow2 = (TextView) findViewById(R.id.solproblemrow2);
TextView solution = (TextView) findViewById(R.id.solutiontextview);
TextView carryover = (TextView) findViewById(R.id.carryovernumbers);
TextView exp1 = (TextView) findViewById(R.id.explain1);
TextView exp2 = (TextView) findViewById(R.id.explain2);
TextView exp3 = (TextView) findViewById(R.id.explain3);
TextView exp4 = (TextView) findViewById(R.id.explain4);
numrow1.setText(TensAdditionExerciseActivity.n1display + "");
numrow2.setText(" " + TensAdditionExerciseActivity.n2display + " +");
explain.add(exp1);
explain.add(exp2);
explain.add(exp3);
explain.add(exp4);
nextstep = (Button) findViewById(R.id.nextstep);
for (int i = 0; i < 4; i++) {
explain.get(i).setVisibility(View.GONE);
}
solution.setVisibility(View.GONE);
carryover.setVisibility(View.GONE);
explain.get(0).setText("test");
setTextViews();
nextButtonsetOnClickListener();
}
protected void nextButtonsetOnClickListener() {
nextstep.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View v) {
explain.get(i).setVisibility(View.VISIBLE);
i++;
if (i > 2 && onesanswer < 10) {
nextstep.setClickable(false);
}
if (i > 3 && onesanswer >= 10) {
nextstep.setClickable(false);
}
}
});
}
protected void setTextViews() {
explain.get(0).setText(
"Add " + (onesnum1) + " and " + (onesnum2) + " which equals "
+ (onesanswer) + ".");
if (onesanswer >= 10) {
explain.get(1).setText(
"Since the answer is 10 or greater, 1 must carry over to the tens place and "
+ onesanswermod + " is left in the ones place.");
explain.get(2).setText(
"Add the tens place digits, " + tensnum1 + " and "
+ tensnum2
+ ". Don't forget to add the carried over 1!");
explain.get(3).setText(
"1 + " + tensnum1 + " + " + tensnum2 + " = "
+ (tensanswer + 1));
} else {
explain.get(1).setText(
"Add the tens place digits: " + tensnum1 + " and "
+ tensnum2 + ".");
explain.get(2).setText(
tensnum1 + " + " + tensnum2 + " = " + tensanswer);
}
Ah, I figured it out. I had my ArrayList set to static rather than final, but I still do not completely the entirety of my error. Would someone be willing to tell me why it made such a big difference?
A static variable / method has only one instance for the entire class. That means, that in the case of your listview, only one exists for all instances of your activity in the entire app, which is why your getting your error. Final means that it can't be initialized anywhere other than the constructor or when the variable is defined. (Difference between Static and final?).