5

I am experiencing a problem in Double value manipulation.

Lets take,

Double d = new Double(123456789987654321123456789d);
System.out.println(d);

The output is :

1.2345678912345678E35

But I want,

123456789987654321123456789

The complete digit without any notation.

I have tried all permutation using BigDecimal, BigInteger and so and so.

Note: I want to populate into JSON so please don't suggest just a print statement.

I have already read :

halfer
  • 19,824
  • 17
  • 99
  • 186
Mohammed Rizwan
  • 51
  • 2
  • 2
  • 6

2 Answers2

9

Try this BigDecimal::toPlainString:

BigDecimal d = new BigDecimal("123456789987654321123456789");
String result = d.toPlainString();

Output of d is :

123456789987654321123456789

To populated to JSon there are many ways, I'm not sure what you want exactly, but maybe this can help you How to create JSON Object using String?:

BigDecimal d = new BigDecimal("123456789987654321123456789");

JSONObject myObject = new JSONObject();
myObject.put("number", d.toPlainString());
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • *Note: I want to populate into JSon so please don't suggest just a print statement* – Lino Dec 14 '17 at 09:15
  • 3
    @Lino Using that value to populate JSON varies based on which JSON library the OP is using. Since the OP didn't share any information about that we can't give him a good answer on how to add this value to a JSON object. – BackSlash Dec 14 '17 at 09:19
  • @BackSlash You're right. @YCF_L Maybe you could provide also a solution that takes a `double` as an argument and not a `String`. As this is probably the use case the OP's having – Lino Dec 14 '17 at 09:19
  • @YCF_L not exactly, but still useful though! I meant the way to create a Bigdecimal from double – Lino Dec 14 '17 at 11:23
  • @Lino do you have a solution maybe? I don't see where is the problem with this way – Youcef LAIDANI Dec 14 '17 at 11:41
  • @YCF_L i mean that maybe the double is generated somehow: `double d = getDouble();` and then create from the variable `d` a `BigDecimal` instance – Lino Dec 14 '17 at 11:46
  • @BackSlash i am new to json , can you pls tell me what is 'JSON varies based on which JSON library the OP is using'? – Mohammed Rizwan Dec 21 '17 at 13:09
  • @YCF_L yeah that is good one, but the problem is i get this value as a function return type so if i convert also it is rounded off. so i cannot use this also. Double d = new Double(123456789987654321123456789d); BigDecimal bd = new BigDecimal(d); now again it is changed... – Mohammed Rizwan Dec 21 '17 at 13:14
  • @MohammedRizwan about JSON you can use [this](https://mvnrepository.com/artifact/org.json/json) or [this](https://mvnrepository.com/artifact/com.google.code.gson/gson) – Youcef LAIDANI Dec 21 '17 at 16:47
1

You can try this

String str = String.format("%.0f", d);

Note that max digits a double can hold is ~17, so 123456789987654321123456789 will rounded

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275