I'm working on a low latency system and need a solution to convert a double number to byte array but with precision for decimal numbers. I need to consider there should be less object creation within the solution. Also, I'm getting value as double.
My current implementation is somewhat like
int offset = 0;
double d = 1211.11;
long integerPart = (long) d;
byte[] b = new byte[16];
offset += addToByteArray(integerPart, b, offset);
//implementation to add each digit to byte array, returns new offset
int lengthDecimal = 16 - offset;
if(lengthDecimal > 0)
b[offset++] = '.';
long tmp = 1;
for(int i=0; i<lengthDecimal; i++){
tmp = tmp * 10;
int digit = (int)(((long) (d * tmp)) % 10);
b[offset++] = (byte) ('0' + digit);
}
Then the byte array is manipulated to trim later zeros and '.' if required.
The problem is if I check the byte array, I don't find the exact digits. Since, I'm using double, the precision of decimal point is lost while working.
I've searched and found everywhere to use BigDecimal. The use of BigDecimal seems to work fine but I'm worried about the performance and number of objects created as this part of the code is hit frequently.
I've also tried to work with String like this
String doubleNumber = Double.toString(d);
long fractionalPart = 0;
offset += addToByteArray(integerPart, b, offset);
if(doubleNumber.substring(doubleNumber.indexOf(".")).length() > 0) {
fractionalPart = Long.valueOf(doubleNumber.substring(doubleNumber.indexOf(".") + 1));
b[offset++] = '.';
offset += addToByteArray(fractionalPart, b, offset);
}
Please suggest me the best approach for the purpose.