我不确定是我还是什么,但我在将double转换为字符串时遇到问题.
这是我的代码:
double total = 44;
String total2 = Double.toString(total);
Run Code Online (Sandbox Code Playgroud)
我做错了什么,或者我错过了一步.
NumberFormatException尝试转换它时出错.
totalCost.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
double priceG = Double.parseDouble(priceGal.getText().toString());
double valG = Double.parseDouble(volGal.toString());
double total = priceG * valG;
String tot = new Double(total).toString();
totalCost.setText(tot);
} catch(Exception e) {
Log.e("text", e.toString());
}
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
我试图在onTouchListener中执行此操作.我发布更多代码,基本上当用户触摸edittext框时,我希望信息计算填充edittext框.
Bha*_*gar 438
double total = 44;
String total2 = String.valueOf(total);
Run Code Online (Sandbox Code Playgroud)
这会将double转换为String
Nic*_* Lu 18
使用Double.toString(),如果数字太小或太大,您将获得如下科学记数:3.4875546345347673E-6.有几种方法可以更好地控制输出字符串格式.
double num = 0.000074635638;
// use Double.toString()
System.out.println(Double.toString(num));
// result: 7.4635638E-5
// use String.format
System.out.println(String.format ("%f", num));
// result: 0.000075
System.out.println(String.format ("%.9f", num));
// result: 0.000074636
// use DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("#,##0.000000");
String numberAsString = decimalFormat.format(num);
System.out.println(numberAsString);
// result: 0.000075
Run Code Online (Sandbox Code Playgroud)
使用String.format()将是最方便的方法.
dit*_*kin 14
此代码编译并适用于我.它使用您尝试的调用将double转换为字符串.
public class TestDouble {
public static void main(String[] args) {
double total = 44;
String total2 = Double.toString(total);
System.out.println("Double is " + total2);
}
}
Run Code Online (Sandbox Code Playgroud)
你看到NumberFormatException让我感到困惑.查看堆栈跟踪.我猜你有其他代码,你没有在你的示例中显示导致该异常被抛出.
| 归档时间: |
|
| 查看次数: |
832643 次 |
| 最近记录: |