使用三个小数位来渲染小数

时间:2012-08-10 04:24:42

标签: android

我正在尝试编写一个程序。它舍入了十进制数字(23.4353353到23.435)。对我来说工作正常。

问题: -

如果我输入23仅数字而不是小数,则仅显示23.0。

如果decimalvalue为3: -

我希望如果像23,40,56 .they这样的任何值显示为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" />

3 个答案:

答案 0 :(得分:2)

使用DecimalFormat

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

示例库在此主题上有a good collection of examples

像这样实施:

double decimalValue = Double.parseDouble(value);
String result = threeZeroes.format(decimalValue);
et1.setText(result);

答案 1 :(得分:1)

et1.setText(String.format("%.3f", getValue(value, decimalPlaces)));

答案 2 :(得分:0)

使用DecimalFormat包中的java.text

DecimalFormat df = new DecimalFormat("#.000");
double d = 45;
System.out.println(df.format(d));