Android String format - price
Is there an easy formatter to format my String as a price?
So my string is: 300000 i'd like to "300 000" with space
开发者_JAVA百科or 1000000 "1 000 000"
Leslie
This does it:
String s = (String.format("%,d", 1000000)).replace(',', ' ');
Use Formatter class to format string
format("%,d", 1024);
After that replace , with space.
http://developer.android.com/reference/java/util/Formatter.html
You cannot do this with a simple format string but with the DecimalFormat
and DecimalFormatSymbols
class.
int value = 123456789;
DecimalFormat fmt = new DecimalFormat();
DecimalFormatSymbols fmts = new DecimalFormatSymbols();
fmts.setGroupingSeparator(' ');
fmt.setGroupingSize(3);
fmt.setGroupingUsed(true);
fmt.setDecimalFormatSymbols(fmts);
TextView txt = (TextView) findViewById(R.id.txt);
txt.setText(fmt.format(value));
There are lots and lots of other options in these classes. For example you could seperate the numbers with dots or commas or use a locale specific setting.
For example you can use the fmt.setCurrency
method:
fmt.setCurrency(Currency.getInstance(Locale.GERMANY));
double yourPrice = 1999999.99;
String formattedPrice = new DecimalFormat("##,##0.00€").format(yourPrice);
output :
formattedPrice = 1.999.99,99€
if you have integer value, most elegant in my opinion
public static String formatNumberWithSpaces(long number) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
return formatter.format(number);
}
精彩评论