I have an integer value that is read from a PLC device via bluetooth and the first digit represent one decimal place. For example: 100 must be formatted to 10.0. Another examples:
500 -> 50.0
491 -> 49.1
455 -> 45.5
The following line will make it okay:
data11.put("Text2", String.format("%.1f", (float)(mArray[18] & 0xFF | mArray[19] << 8) / 10.0));
But... Is there another way to do the same using String.format without divide by 10.0?
Thank you
How about the following way?
x = x.substring(0, x.length() - 1) + "." + x.substring(x.length() - 1);
If your concern is the internal rounding that happens with a float representation, consider using BigDecimal
. Like:
BigDecimal v = BigDecimal.valueOf(500,1);
System.out.println(v.toString());
or combined as
System.out.println(BigDecimal.valueOf(500,1).toString());
or maybe you need to use
System.out.println(BigDecimal.valueOf(500,1).toPlainString());
And to answer your original question directly, even this works:
BigDecimal v11 = BigDecimal.valueOf(mArray[18] & 0xFF | mArray[19] << 8,1);
data11.put("Text2", String.format("%.1f", v11));
But the real question is if this is all really needed or not.
How about this?
System.out.println(500*0.1);
System.out.println(491*0.1);
System.out.println(455*0.1);
Output
50.0
49.1
45.5
I would go by integer division and modulo:
private static String format(int value) {
return (value / 10) + "." + Math.abs(value % 10);
}
Math.abs()
can be removed if not using negative numbers:
private static String format(int value) {
return (value / 10) + "." + (value % 10);
}
Obviously the method can be inlined...