Formatting Integer with a decimal point

2019-09-13 20:02发布

问题:

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

回答1:

How about the following way?

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



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



回答3:

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 


回答4:

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