236

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.

guerda
  • 23,388
  • 27
  • 97
  • 146
Brandon Wilson
  • 4,462
  • 7
  • 60
  • 90
  • 5
    Seems fine to me, what problem have you encountered? – MByD Apr 23 '11 at 19:16
  • 2
    is that the real code your are executing? those lines work perfect. – mcabral Apr 23 '11 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 '11 at 19:18
  • 1
    There must be something else, this should work just fine. http://ideone.com/btGrv – Kevin Apr 23 '11 at 19:18
  • I am not familiar with android sdk, do you think it needs to be `44.00`? The reason why I say that he is getting a `NumberFormatException` which could only mean that it thinks it's not a double. – CoolBeans Apr 23 '11 at 19:23
  • doesn't look like any problem here, are you sure problem is at `Double.toString()` ? – kdabir Apr 23 '11 at 19:24
  • @CoolBeans - google says, no. It can't throw that. http://developer.android.com/reference/java/lang/Double.html – Brian Roach Apr 23 '11 at 19:26
  • 1
    Show stacktrace and whole code – Bozho Apr 23 '11 at 19:28
  • @Brian Roach - thanks. I was just thinking out loud. The exception must be generating for some other place then. – CoolBeans Apr 23 '11 at 19:28

17 Answers17

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

This will convert double to String

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Bhavit S. Sengar
  • 8,794
  • 6
  • 24
  • 34
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.

Nicholas Lu
  • 1,655
  • 15
  • 14
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.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
ditkin
  • 6,774
  • 1
  • 35
  • 37
  • 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 '11 at 19:26
  • 1
    So does the OP's code. There isn't a problem here to be solved. – Brian Roach Apr 23 '11 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. – Brandon Wilson Apr 23 '11 at 19:38
6

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

Stephan
  • 7,360
  • 37
  • 46
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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
agon
  • 41
  • 1
2

Kotlin

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

val d : Double = 100.00
val string : String = d.toString()
Community
  • 1
  • 1
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
2
double total = 44;
String total2 = new Double(total).toString();
spongebob
  • 8,370
  • 15
  • 50
  • 83
olyanren
  • 1,448
  • 4
  • 24
  • 42
  • 4
    `Double.toString()` calls `String.valueOf(double)` which calls `Double.toString(double)`. Crazy, eh? – corsiKa Apr 23 '11 at 19:26
  • So does the OP's code. There isn't a problem here to be solved. – Brian Roach Apr 23 '11 at 19:27
  • 2
    @Muhammed - Possible?? *It's what it does* – Brian Roach Apr 23 '11 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. – Brian Roach Apr 23 '11 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 '11 at 19:33
  • Apart from the mentioned issues, this will convert to a power of ten representation for big decimals. – AlexCode Jul 04 '14 at 08:54
2

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

double total = 44;
String total2 = "" + total;
EJZ
  • 1,142
  • 1
  • 7
  • 26
  • 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. – Brandon Wilson Apr 10 '22 at 01:29
1

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

  • you should consider that sometimes it will return number with E scientific notation like -2.23561E5 – Augustas Sep 11 '17 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);
Community
  • 1
  • 1
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • I changed the total to a hard number like 44 and it still gave me an error. – Brandon Wilson Apr 23 '11 at 20:37
  • what "total"? Your original code snippit couldn't throw that exception. The two calls I show above can. One of your `String`s isn't a valid representation of a `double` which is why you're getting that exception. – Brian Roach Apr 23 '11 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. – Brian Roach Apr 23 '11 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. – Brandon Wilson Apr 23 '11 at 21:32
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);
ngg
  • 1,493
  • 19
  • 14
0

Just use the following:

doublevalue+""; 

This will work for any data type.

Example:

Double dd=10.09;
String ss=dd+"";
Littm
  • 4,923
  • 4
  • 30
  • 38
  • 7
    Very bad habit to stringify by adding to an empty String. Use dedicated JDK func instead – StackHola Jan 15 '14 at 14:46
  • 3
    @Michael.P why is it bad? – gab06 Jan 18 '15 at 13:37
  • I've been doing this for like all my time as a java programmer lol. – gab06 Jan 18 '15 at 13:38
  • Desugars to String ss=new StringBuilder(String.valueOf(dd)).append(""); – dsmith May 20 '15 at 21:37
  • 1
    Unless there is some compile-time optimization at play, it would call an additional constructor and append method. – dsmith May 20 '15 at 21:51
  • It first creates a new String with `new String(new char[] {})`, then uses `Double.toString()` to convert the double into a string, and then does `String.concat()` to add the two together. Two extra operations. It's not good to use this method. Simple, but effective for causing lag. – hyper-neutrino Aug 29 '15 at 02:06
  • 1
    Always use String.valueOf(dd) instead. This will also work for any data type. – BladeCoder Oct 26 '15 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.

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
REMITH
  • 1,049
  • 12
  • 12
-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.

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
-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();
Vihan Gammanpila
  • 346
  • 4
  • 10
  • Identical content [at Digital Ocean](https://www.digitalocean.com/community/tutorials/java-convert-double-to-string) (likely plagiarised from the same place). – Peter Mortensen Sep 04 '22 at 14:28