Question

I have

String number = 1.0E7;

I want its numeric equivalent i.e display it as a

double x = 10000000.0000 

How can I go about it?

I have tried Double number = Double.valueOf(number);

but getting java.lang.NumberFormatException.

Was it helpful?

Solution 3

To format a number with 4 decimals, use String.format("%.4f", num) as in the following example:

public class k {

  public static void main(String argv[]) {
    String number = "1.0E7";
    Double num = Double.valueOf(number);
    System.out.println("Double="+ num + " Formatted Double=" + String.format("%.4f", num));
  }
}

Output:

String=1.0E7 Formatted Double=10000000,0000

As you can see, my locale uses , as decimal separator.

OTHER TIPS

You want to format a double value.

String it = String.format("%f", 1.0e7);

should do it.

This will work perfectly.

double number=1.0E7;
System.out.println(number);
NumberFormat formatter=new DecimalFormat();
System.out.println(formatter.format(number));

If you look at the docs of Double#toString(double), you can see that

If m is less than 10-3 or greater than or equal to 107, then it is represented in so-called "computerized scientific notation.

That is why even if you parse the value to a double, you'll get the scientific notation only, which is 1.0E7.

You can do something like this to print the double value as you want.

String number = "1.0E7";
String desiredFormat = String.format("%f", Double.parseDouble(number));
System.out.println(desiredFormat); // Prints 10000000.000000

Or may be use a NumberFormat if you want.

String number = "1.0E7";
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(Double.parseDouble(number)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top