Stillie
Stillie

Reputation: 2676

Is there a better way to display % in Android

Currently, I am displaying a value as a Percent by simply setting text as below:

mInterestRateEditText.setText(i + "%");

Is there a better way to do this? I have tried with DecimalFormat method like this:

private String displayPerc(int perc) {
     DecimalFormat df = new DecimalFormat("#%");
     return df.format(perc);
}

But for some reasons when i = 1 it displays 100%.

Is there a better way to display % other than concatenating the symbol at the end?

Thanks

Upvotes: 1

Views: 79

Answers (1)

Ankit Aggarwal
Ankit Aggarwal

Reputation: 5375

Declare a string in strings.xml

<string name="percentage">%1$f %</string>

and set it in your code with

mInterestRateEditText.setText(getString(R.string.percentage, i));

EDIT : To do it the decimal format way, do

private String displayPerc(int perc) {
  DecimalFormat df = new DecimalFormat("#'%'");
  return df.format(perc);
} 

put '%' instead of %. Normal % will Multiply by 100 and show as percentage. Check this link http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

Upvotes: 4

Related Questions