2

I need to parse String to Double, but with my current code i am getting exponential notation in it

String str = "10000000";
Double parsedString = Double.valueOf(str);

It's giving me 1.0E7. I need output 10000000

Any help?

  • That is just how `Double` is stored, if you want to _print_ it with different values, format the printing output. Something like `System.out.printf("%8.0f", parsedString);`. or using `DecimalFormat` – Nexevis Oct 18 '19 at 14:02
  • 6
    Possible duplicate of [How do I print a double value without scientific notation using Java?](https://stackoverflow.com/questions/16098046/how-do-i-print-a-double-value-without-scientific-notation-using-java) – vahdet Oct 18 '19 at 14:05
  • You can use "new BigDecimal(str)" if you don't want to use formatter. – Ashok Prajapati Oct 18 '19 at 14:30
  • @AshokPrajapati Thanks a lot. yes you are correct. I have tried with BigDecimal and it gives output that I am expecting. It also supports marshalling so can use it. –  Oct 18 '19 at 16:19
  • @vahdet nope, the 2 questions are different. I want to convert string to double and not want to print double –  Oct 18 '19 at 16:20
  • @Nexevis yup, you are correct that Double is stored in this way, it internally invokes parseDouble(String) and while parsing adds Exponential notation. I wanted somekind of logic to get things work. But anyways thanks –  Oct 18 '19 at 16:21

2 Answers2

1

you can call a method for this.

Double parseStringToDouble = validate(str);

The definition of validate method will be

private Double validate(String s) {
  try{
    return Double.valueOf(s);
  } catch(NumberFormatException nfe){
    // you can throw your custom exception here.
  }
}

With this you will not get any exponential notation.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Aditya
  • 950
  • 8
  • 37
0

This is the way Double numbers are displayed. If you want to display number in a different way you have to format it:

System.out.printf("%.0f", number);