0

可能重复:
如何很好地将浮动类型格式化为字符串?

如何列出最多两位小数的数字?我试过这个方法: http: //developer.android.com/reference/java/text/NumberFormat.html但没有运气。下面的代码。也许有人可以帮助我。

package karcio.fuel.economy;


public class FuelEconomy extends Activity 
{
    private EditText editText1;
    private EditText editText2;

private TextView textView4;
private TextView textView6;

private Button button1;

private double miles;
private double liters;
private double result;
private double convertMilesToKm;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initParams();
}

private void initParams()
{
    editText1 = (EditText)findViewById(R.id.editText1);
    editText2 = (EditText)findViewById(R.id.editText2);

    textView4 = (TextView)findViewById(R.id.textView4);
    textView6 = (TextView)findViewById(R.id.textView6);

    button1 = (Button)findViewById(R.id.button1);

    button1.setOnClickListener(new Button.OnClickListener() 
    { 
        public void onClick (View v)
        { 
            calculate(); 
        }
    });

}

private void calculate()
{
    miles = Double.parseDouble(editText1.getText().toString());
    liters = Double.parseDouble(editText2.getText().toString());

    convertMilesToKm = miles * 1.61;
    result = 100 * liters / convertMilesToKm;

    textView6.setText(Double.toString(convertMilesToKm));
    textView4.setText(Double.toString(result));         
}

}

4

2 回答 2

4

你可以这样做:

String str = String.format("%.2f", 3.99999);
textView.setText(str);
于 2012-08-30T20:51:54.863 回答
1

好吧,您可以尝试手动执行此操作。

//This is just an example
double number = result;  //result is YOUR variable (ex. result = 23.1231231241920312)
int tmp = number * 100;   //2312.31231241920312
number = (double)tmp / 100;  //23.12

希望这可以帮助。

注意:如果您在另一行执行,您可以跳过我声明 INT 的步骤。

更新:使用这种方法的好处是你不需要创建一个更快的对象,但是当然有很多方法。

于 2012-08-30T20:52:19.437 回答