235

I am not sure it is me or what but I am having a problem converting a double to string.

here is my code:

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

Am i doing something wrong or am i missing a step here.

I get error NumberFormatException when trying to convert this.

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

I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.

9
  • 5
    Seems fine to me, what problem have you encountered?
    – MByD
    Apr 23, 2011 at 19:16
  • 2
    is that the real code your are executing? those lines work perfect.
    – mcabral
    Apr 23, 2011 at 19:18
  • 1
    Double.toString(double) can't even throw NumberFormatException - are you sure the exception isn't being thrown from somewhere else?
    – Random832
    Apr 23, 2011 at 19:18
  • 1
    There must be something else, this should work just fine. ideone.com/btGrv
    – Kevin
    Apr 23, 2011 at 19:18
  • 1
    Show stacktrace and whole code
    – Bozho
    Apr 23, 2011 at 19:28

17 Answers 17

494
double total = 44;
String total2 = String.valueOf(total);

This will convert double to String

5
  • 31
    have the following in mind if total = 1234567890123456 then the String becomes "1.234567890123456E15" which is very often not what you want Nov 29, 2016 at 13:03
  • 7
    any solution for above one? Aug 4, 2017 at 10:20
  • 8
    @PrashanthDebbadwar Yes: NumberFormat fmt = NumberFormat.getInstance(); fmt.setGroupingUsed(false); fmt.setMaximumIntegerDigits(999); fmt.setMaximumFractionDigits(999); then use total2 = fmt.format(total)
    – Andreas
    Aug 15, 2018 at 23:57
  • This internally calls Double.toString(). Not sure how it answers the question.
    – shmosel
    Mar 4, 2019 at 21:14
  • String.format ("%.0f", bigDouble)
    – KevinBui
    Feb 25, 2022 at 15:21
35

Using Double.toString(), if the number is too small or too large, you will get a scientific notation like this: 3.4875546345347673E-6. There are several ways to have more control of output string format.

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

Use String.format() will be the best convenient way.

14

This code compiles and works for me. It converts a double to a string using the calls you tried.

public class TestDouble {

    public static void main(String[] args) {
        double total = 44;
        String total2 = Double.toString(total);

        System.out.println("Double is " + total2);
    }
}

I am puzzled by your seeing the NumberFormatException. Look at the stack trace. I'm guessing you have other code that you are not showing in your example that is causing that exception to be thrown.

3
  • I am puzzled by your seeing the NumberFormatException. Look at the stack trace. I'm guessing you have other code that you are not showing in your example that is causing that exception to be thrown.
    – ditkin
    Apr 23, 2011 at 19:26
  • 1
    So does the OP's code. There isn't a problem here to be solved. Apr 23, 2011 at 19:28
  • possible, I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box. Apr 23, 2011 at 19:38
6

The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.

3
double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

it works. got to be repetitive.

2

Kotlin

You can use .toString directly on any data type in kotlin, like

val d : Double = 100.00
val string : String = d.toString()
2
double total = 44;
String total2 = new Double(total).toString();
6
  • 4
    Double.toString() calls String.valueOf(double) which calls Double.toString(double). Crazy, eh?
    – corsiKa
    Apr 23, 2011 at 19:26
  • So does the OP's code. There isn't a problem here to be solved. Apr 23, 2011 at 19:27
  • 2
    @Muhammed - Possible?? It's what it does Apr 23, 2011 at 19:29
  • @Muhammed - no, it's not efficient. See glowcoder's comment. You're creating a new Double object then calling its toString() method which calls String.valueOf(double) which finally does what the OP did in the first place. Apr 23, 2011 at 19:32
  • 2
    @Muhammed well, you're creating an object just to get its String value. If this were in a loop of some kind, you could experience a lot of additional (unnecessary) overhead. I'm not a big fan of premature optimization, but I am a fan of avoiding obvious deficiencies.
    – corsiKa
    Apr 23, 2011 at 19:33
2

This is a very old post, but this may be the easiest way to convert it:

double total = 44;
String total2 = "" + total;
1
  • I agree my post is old now... However, using double quotes is very common way to convert values to strings. Not sure in Java these days, but in JavaScript, I often do var total = 44; var strTotal = total + "" to make it a string. Or .toString() if I really need to call it out. Apr 10, 2022 at 1:29
1
double priceG = Double.parseDouble(priceGal.getText().toString());
double valG = Double.parseDouble(volGal.toString());

One of those is throwing the exception. You need to add some logging/printing to see what's in volGal and priceGal - it's not what you think.

4
  • I changed the total to a hard number like 44 and it still gave me an error. Apr 23, 2011 at 20:37
  • what "total"? Your original code snippit couldn't throw that exception. The two calls I show above can. One of your Strings isn't a valid representation of a double which is why you're getting that exception. Apr 23, 2011 at 21:01
  • To be clear; Double.toString(total); can not throw an exception. Ever.. You changed that to new Double(total).toString(); which also can't and if you see the answer here that's been voted down it is not something you ever want to do. Apr 23, 2011 at 21:06
  • ok ill get that changed. I moved that litle bit of code out of the ontouchlistener and it worked fine. but when it is in the ontouchlistener it throws the error. I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box. Apr 23, 2011 at 21:32
1

double.toString() should work. Not the variable type Double, but the variable itself double.

1
  • you should consider that sometimes it will return number with E scientific notation like -2.23561E5
    – Augustas
    Sep 11, 2017 at 11:09
1

Complete Info

You can use String.valueOf() for float, double, int, boolean etc.

double d = 0;
float f = 0;
int i = 0;
short i1 = 0;
char c = 0;
boolean bool = false;
char[] chars = {};
Object obj = new Object();


String.valueOf(d);
String.valueOf(i);
String.valueOf(i1);
String.valueOf(f);
String.valueOf(c);
String.valueOf(chars);
String.valueOf(bool);
String.valueOf(obj);
1

There are three ways to convert double to String.

  1. Double.toString(d)
  2. String.valueOf(d)
  3. ""+d

    public class DoubleToString {

    public static void main(String[] args) {
        double d = 122;
        System.out.println(Double.toString(d));
        System.out.println(String.valueOf(d));
        System.out.println(""+d);
    
    }
    

    }

String to double

  1. Double.parseDouble(str);
0

Just use the following:

doublevalue+""; 

This will work for any data type.

Example:

Double dd=10.09;
String ss=dd+"";
7
  • 7
    Very bad habit to stringify by adding to an empty String. Use dedicated JDK func instead
    – StackHola
    Jan 15, 2014 at 14:46
  • 3
    @Michael.P why is it bad?
    – gab06
    Jan 18, 2015 at 13:37
  • I've been doing this for like all my time as a java programmer lol.
    – gab06
    Jan 18, 2015 at 13:38
  • 1
    Unless there is some compile-time optimization at play, it would call an additional constructor and append method.
    – dsmith
    May 20, 2015 at 21:51
  • 1
    Always use String.valueOf(dd) instead. This will also work for any data type.
    – BladeCoder
    Oct 26, 2015 at 14:19
0

How about when you do the

totalCost.setText(tot);

You just do

totalCost.setText( "" + total );

Where the "" + < variable > will convert it to string automaticly

0

When you would like to format the decimal and convert it to a String DecimalFormat helps much.

Example:

DecimalFormat format = new DecimalFormat("#.####");
format.format(yourDoubleObject);

enter image description here

These are various symbols that are supported as part of pattern in DecimalFomat.

-1

Use StringBuilder class, like so:

StringBuilder meme = new StringBuilder(" ");

// Convert and append your double variable
meme.append(String.valueOf(doubleVariable));

// Convert string builder to string
jTextField9.setText(meme.toString());

You will get you desired output.

-1

This is a very old post, but java double to string conversion can be done in many ways, I will go through them one by one with example code snippets.

1. Using + operator

This is the easiest way to convert double to string in java.

double total = 44;
String total2 = total + "";

2. Double.toString()

We can use Double class toString method to get the string representation of double in decimal points. Below code snippet shows you how to use it to convert double to string in java.

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

3. String.valueOf()

double total = 44;
String total2 = String.valueOf(total); 

4. new Double(double l)

Double constructor with double argument has been deprecated in Java 9, but you should know it.

double total = 44;
//deprecated from Java 9, use valueOf for better performance
String total2 = new Double(total).toString();

5. String.format()

We can use Java String format method to convert double to String in our programs.

double total = 44;
String total2 = String.format("%f", total);

6. DecimalFormat

We can use DecimalFormat class to convert double to String. We can also get string representation with specified decimal places and rounding of half-up.

double total = 44;
String total2 = DecimalFormat.getNumberInstance().format(total);

//if you don't want formatting
total2 = new DecimalFormat("#.0#").format(total); // rounded to 2 decimal places

total2 = new DecimalFormat("#.0#").format(44); // rounded to 2 decimal places

7. StringBuilder, StringBuffer

We can use StringBuilder and StringBuffer append function to convert double to string.

double total = 44;
String total2 = new StringBuilder().append(total).toString();
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.