Reputation: 59
I'm writing a simple Percentage Calculator android app in Android Studio. Here's my psuedo:
resultView = (TextView) findViewById(R.id.ResultView);
percentageText = (EditText) findViewById(R.id.PercentageInput);
numberText = (EditText) findViewById(R.id.NumberInput);
Button calcButton = (Button) findViewById(R.id.Calculate_btn);
calcButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
if(percentageText.length() != 0 && numberText.length() != 0)
{
float percentage = Float.parseFloat(percentageText.getText().toString()) / 100;
float result = percentage * Float.parseFloat(numberText.getText().toString());
resultView.setText(Float.toString(result));
}
else if(percentageText.length() == 0 && numberText.length() == 0)
{
resultView.setText("Don't be dumb...");
}
}
});
so it seemed like everything was working fine. Simple percentages are always right. 50%100=50, 25%50=12.5 ... but then I get to 3 and 6. 3%10= 0.29999998 ... shouldn't it be .3? and 60%100= 60.000004 ... Any help out there?
Upvotes: 1
Views: 92
Reputation: 6274
It has to do with the fact that double
variables have a limited number of bits. This is like saying 1/3 = 0.33333333
when really is should be equal to 0.33333333...
forever!
Read about Floating points and Double precision
Upvotes: 4