Trouble Converting Value to Decimal JAVA (Android)
I am currently working on an app for Android. In this app, I need to convert a calculated number to a percentage. The original number (tipTotal) is calculated correctly, but when I try to convert to decimal by dividing by 100 (tipPercentage), tipPercentage is always 0.0.
I have confirmed that tipTotal is correct and what I expect.
public void onClick(View view) {
int tipTotal = 0;
float totalBill = 0;
float tipPercentage = 0;
String time, attitude, refills, clearing, accuracy, bill;
time = timeSpinner.getSelectedItem().toString();
attitude = attitudeSpinner.getSelectedIte开发者_开发技巧m().toString();
refills = refillsSpinner.getSelectedItem().toString();
clearing = clearingSpinner.getSelectedItem().toString();
accuracy = accuracySpinner.getSelectedItem().toString();
bill = txtBill.getText().toString();
tipTotal = Integer.parseInt(time)+Integer.parseInt(attitude)+Integer.parseInt(refills)+Integer.parseInt(clearing)+Integer.parseInt(accuracy);
tipPercentage = tipTotal / 100;
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, String.valueOf(tipPercentage), duration);
toast.show();
}
Thanks for your help!
Try this:
tipPercentage = ((float)tipTotal)/ 100f;
The problem could be that tipTotal / 100
is doing an integer division... which has no decimal part, and which is less than 1. That's how integer divisions works... for instance: 10/6 = 1
. On the other hand 10f/6f=1.6666
.
I'll second Cristian's reply, it almost certainly is because tipTotal / 100
is an integer division, which in your case seems to be returning int 0
which is then type cast to float 0.0
So one way to resolve this would be to take Cristian's suggestion and force division of two floats.
The other option is to declare tipTotal
as float tipTotal = 0;
in which case the division would proceed as per your expectation since 100
will be automatically promoted to float.
EDIT: To gain a better understanding check out http://mindprod.com/jgloss/division.html
精彩评论