我正在尝试编写一个程序。将十进制数字四舍五入(23.4353353 到 23.435)。它对我来说很好用。
问题:-
如果我只输入 23 位数字,没有小数点,它只显示 23.0。
如果十进制值为 3:-
我想要任何像 23,40,56 这样的值。他们应该显示 ilke 23.000 ,40.000
public class ProjectDecimalActivity extends Activity {
public static EditText et1;
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et1 =(EditText)findViewById(R.id.textView1);
btn =(Button)findViewById(R.id.btn1);
}
public void onclick(View v)
{
String value = et1.getText().toString();
int decimalvalue = 3;
et1.setText(getValue(value, decimalPlaces).toString());
}
public static Float getValue(String value, int decimalvalue)
{
Float retVal = null;
try
{
float floatValue = Float.parseFloat(value);
//look for decimal point
int index = value.indexOf('.');
if (index >= 0)
{
String fractional = value.substring(index);
//do the round off only when the fraction length
//is greater than decimal places
if (fractional.length() > decimalvalue)
{
floatValue = roundOff(floatValue, decimalPlaces);
}
}
returnvalvalue = new Float(floatValue);
}
catch(NumberFormatException nfe)
{
//do nothing
}
return retVal;
}
public static float roundOff(float value, int decimalPlaces)
{
float returnvalvalue = value;
float factor = 1;
for (int i = 0; i < decimalPlaces; i++)
{
factor *= 10;
}
float roundFactor = 5/(factor*10);
int intFactor = (int) ((value + roundFactor) * (factor));
returnvalvalue = (float) intFactor/(factor);
return returnvalvalue ;
}}
我的 xml 代码是:-
<EditText
android:id="@+id/textView1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:inputType="numberDecimal" />
<Button
android:id="@+id/btn1"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onclick"
android:text="click" />