How do I use the NumberFormat & maxDecimalFraction() functions?
I want to format the text sent to a edittext box so that at most 2 decimal places are shown, e.g. XXX.00. From the developer.android site I've been able to create the format variable (or is it a enum?) as follows:
NumberFormat nf = new NumberFormat;
nf.setMaximumFractionDigits(2);
I tried to format my string s = nf.format(s); but it doesn't work. How do I format a string vaiable with the nf to prepare it for a edittext box?
Also, how am I supposed to figure this out from the developers.android site for "NumberFormat"? Is there a way to read t开发者_JS百科he site to figure this out, or is the site simply incomplete?
Try this. Your code looks incomplete. The NumberFormat documentation looks complete to me.
NumberFormat nf = NumberFormat.getInstance(); // get instance for your locale
nf.setMaximumFractionDigits(2); // set decimal places
String s = nf.format(100.0232); // the parameter must be a long or double
I have created a method that I use for formatting my text:
public static String formatDouble(double doubleToFormat, int min, int max) {
NUMBER_FORMAT.setMaximumFractionDigits(max);
NUMBER_FORMAT.setMinimumFractionDigits(min);
return NUMBER_FORMAT.format(doubleToFormat);
}
Here is my NUMBER_FORMAT
field:
public static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();
And to use it:
myEditText.setText(formatDouble(153.141254, 2, 2));
result text in myEditText
: 153.14
using this function(formatDouble
), you can send any min or max value you desire
精彩评论