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.
Casting double to byte Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).
round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.
byte[] bytes = new byte[8];
java.nio.ByteBuffer.wrap(bytes).putDouble(yourDouble);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With