0

I am getting a strange problem while parsing a double from String of length greater than 7.

For example: The String contains the value:

String str = '123456789'

When I run the following code:

double d = Double.parseDouble(str);
System.out.println(d);

The output is:

1.23456789E8

The value stored in the database is:

123456789.0000000000000000

The data type of column is decimal(40,16)

And there is no exception generated. Please let me know how can I handle it.

Mehmood Memon
  • 1,129
  • 2
  • 12
  • 20
  • 3
    Seems ok to me (except for the wrong quotes used to define the string), where do you see a problem? – Henry Jan 26 '16 at 06:34
  • 1
    1.23456789E8 = 1.23456789 * 10^8 = 123456789 = 123456789.0000000000000000 - No problem there. – Florian Schaetz Jan 26 '16 at 06:35
  • The problem is that I have to display the same value on my website and over there it shows 1.23456789E8 – Mehmood Memon Jan 26 '16 at 06:35
  • 1
    Possible duplicate of [Convert double to String in Java](http://stackoverflow.com/questions/25067808/convert-double-to-string-in-java) –  Jan 26 '16 at 06:37

5 Answers5

3

1.23456789E8 is 1.23456789 x 10 ^8^, so the result looks as it should.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
2

1.23456789E8 is in scientfic format and can be read as 1.23456789 * Math.pow(10,8)

To print in decimal format use:

System.out.printf("%f", d);
Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43
1

To get a differently formatted output use for example

System.out.printf("%15.7f%n", d);
Henry
  • 42,982
  • 7
  • 68
  • 84
1
String str = "123456789";
double d = Double.parseDouble(str);
System.out.printf("%f\n", d);// print 123456789.000000 

See also How to print double value without scientific notation using Java?

Community
  • 1
  • 1
mmuzahid
  • 2,252
  • 23
  • 42
1

Try this out, this will help you what you want.

new BigDecimal(d).toPlainString()
Sindhoo Oad
  • 1,194
  • 2
  • 13
  • 29
  • Thanks. The output is fine now. – Mehmood Memon Jan 26 '16 at 07:30
  • This way of doing it will give you unexpected results for most non-integer values of `d`. To get your `double` looking the same as what's in your database, using `BigDecimal`, you'd be better to write `BigDecimal.valueOf(d).toPlainString()`. – Dawood ibn Kareem Jan 26 '16 at 10:13
  • @DavidWallace I appreciate that you want to make ans better, I havent tried that approach, if you are confirm then you can edit that ans, so that other can be beneficiary from it. – Sindhoo Oad Jan 27 '16 at 04:32