将双精度转换为字符串

2022-08-31 05:49:42

我不确定是我还是别的什么,但我在将双精度转换为字符串时遇到问题。

这是我的代码:

double total = 44;
String total2 = Double.toString(total);

我做错了什么,还是我在这里错过了一步。

尝试转换此内容时出现错误。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;
  }         
});

我正在尝试在onTouchListener中执行此操作。Ill post更多的代码,基本上当用户触摸编辑文本框时,我想要的信息来计算一个填充编辑文本框。


答案 1
double total = 44;
String total2 = String.valueOf(total);

这会将 double 转换为 String


答案 2

使用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

使用 String.format() 将是最方便的方法。


推荐