1

我正在尝试编写一个程序。将十进制数字四舍五入(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" />
4

3 回答 3

2

使用DecimalFormat.

DecimalFormat threeZeroes = new DecimalFormat("#0.000");
double x = 505.0;
String result = threeZeroes.format(x);
Log.i("RESULT", result); // Prints "505.000"

Example Depot 有很多关于这个主题的例子。

像这样实现它:

double decimalValue = Double.parseDouble(value);
String result = threeZeroes.format(decimalValue);
et1.setText(result);
于 2012-08-10T04:29:14.547 回答
1
et1.setText(String.format("%.3f", getValue(value, decimalPlaces)));
于 2012-08-10T04:35:45.730 回答
0

DecimalFormatjava.text包装中使用。

DecimalFormat df = new DecimalFormat("#.000");
double d = 45;
System.out.println(df.format(d));
于 2012-08-10T04:38:54.970 回答