简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM