2

I'm trying to convert double precision number to decimal . for example the number 22 in double precision and as bytes are :

[0] 0
[1] 0
[2] 0
[3] 0
[4] 0
[5] 0
[6] 54
[7] 64

now I try to convert these values again to 22 :

  ByteBuffer buffer = ByteBuffer.wrap(data);
  long l = buffer.getLong();
  long b = Double.doubleToLongBits(l);

but the result is something totally wrong :4.6688606E18 what's this number ? please help , I'm totally confused!

according to IEEE Standard 754 for double precision:

Any value stored as a double requires 64 bits, formatted as shown in the table below:

63 Sign (0 = positive, 1 = negative)

62 to 52 Exponent, biased by 1023

51 to 0 Fraction f of the number 1.f

now how should I convert double precision to numbers to get 22 again ? all of these answers are wrong

melisa zand
  • 211
  • 2
  • 6
  • 16

2 Answers2

2

I'm not sure exactly what sort of conversion you're trying to do (when you say "convert to decimal", what is your desired output format/class?)

However, my first thought reading the title was that a BigDecimal would be a valid representation. So the first approach would be to do something like the following:

double d = ...; // your input number
BigDecimal b = new BigDecimal(d);

That said, if you want to convert to decimal then it's presumably because there are floating ponit/rounding issues with the value of d, which will still be present in the BigDecimal representation as it's being constructed based on d.

The best approach to get around this is to use BigDecimals from the get-go, using their String constructor - so there won't be any instances of floating-point rounding. If this isn't an option for whatever reason, you can convert the double to a string in such a way that it will account for many floating point rounding issues:

String strRep = Double.toString(d);
BigDecimal b = new BigDecimal(strRep);
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • 1
    Was going to point out `String` as a way to keep precision but you beat me to it! Nice answer. – Frankie Jun 01 '12 at 11:59
0

You can write simple test (with JUnit):

double initial = 22.0;

long bits = Double.doubleToLongBits(initial);

double converted = Double.longBitsToDouble(bits);

assertEquals(Double.valueOf(initial), Double.valueOf(converted));

If this works - check you have correct byte representation for 22 (correct representation will be at bits variable).

alexey28
  • 5,170
  • 1
  • 20
  • 25