Format Doubles to String [duplicate]

狂风中的少年 提交于 2019-12-12 03:49:31

问题


Possible Duplicate:
How to nicely format floating types to String?

How can I list the number with up to two decimal places? I tried this method: http://developer.android.com/reference/java/text/NumberFormat.html but no luck. Below code. Maybe someone can help me.

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));         
}

}


回答1:


You can do something like this:

String str = String.format("%.2f", 3.99999);
textView.setText(str);



回答2:


Well you can try to manually do it.

//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

Hope this helps.

Note: You can skip the step where i declare an INT if you do it on the other line.

Update: The advantage of using this method is that you do not need to create an Object which is faster, but of course there are many ways.



来源:https://stackoverflow.com/questions/12205190/format-doubles-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!