0

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Madbyte
  • 95
  • 9

4 Answers4

3

How about the following way?

x = x.substring(0, x.length() - 1) + "." + x.substring(x.length() - 1);

VHS
  • 9,534
  • 3
  • 19
  • 43
  • I like it. It won’t give what I think you would want if the number was 0, but this special case can be handled with `if`-`else` if needed. – Ole V.V. Mar 15 '17 at 18:15
2

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.

YoYo
  • 9,157
  • 8
  • 57
  • 74
1

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 
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

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...

user85421
  • 28,957
  • 10
  • 64
  • 87