Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting double to string

Tags:

java

android

People also ask

How do I convert a double array to a string?

You can convert a double array to a string using the toString() method. To convert a double array to a string array, convert each element of it to string and populate the String array with them.

How do I convert a double to a string in C++?

A double can be converted into a string in C++ using std::to_string. The parameter required is a double value and a string object is returned that contains the double value as a sequence of characters.

Can you convert string to double in java?

We can parse String to double using parseDouble() method. String can start with “-” to denote negative number or “+” to denote positive number. Also any trailing 0s are removed from the double value. We can also have “d” as identifier that string is a double value.


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

This will convert double to String


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.


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.


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


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.


Kotlin

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

val d : Double = 100.00
val string : String = d.toString()

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