Pol Hallen
Pol Hallen

Reputation: 1872

percentage of 2 numbers

I build a simple texteditor, I also add a percentage of reading. I think is everything ok (on my mobile and 3 emulators) but on other devices crashes.

I don't understand what is the problem. Any help?

public void perc(){
    float perc3;
    perc3=((a)*100)/(float)b;
    NumberFormat numberFormat = DecimalFormat.getInstance();
    numberFormat.setMaximumFractionDigits(2);
    String formattedText = numberFormat.format(perc3);
    perc= new Double(formattedText);
}

Upvotes: 0

Views: 103

Answers (1)

Rubms
Rubms

Reputation: 745

If, as you state, you're sure b is never going to be 0, why don't you try a different approach to get the 2 fraction digits double? It seems less error prone and more efficient:

public double perc()
{
   long perc3 = Math.round( a*10000 / (double)b );
   return perc3 / (double) 100;
}

I hope this helps. If you still get a crash I'm quite sure it is not in this snippet of code.

Upvotes: 1

Related Questions