将double转换为字符串

Bra*_*son 193 java android

我不确定是我还是什么,但我在将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

  • 如果总计= 1234567890123456,请记住以下内容,然后字符串变为"1.234567890123456E15",这通常不是您想要的 (22认同)
  • 任何上述解决方案? (6认同)
  • @PrashanthDebbadwar是:`NumberFormat fmt = NumberFormat.getInstance(); fmt.setGroupingUsed(假); fmt.setMaximumIntegerDigits(999); fmt.setMaximumFractionDigits(999);`然后使用`total2 = fmt.format(total)` (6认同)

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让我感到困惑.查看堆栈跟踪.我猜你有其他代码,你没有在你的示例中显示导致该异常被抛出.


Ste*_*han 6

异常可能来自parseDouble()调用.检查给予该函数的值是否真的反映了double.