Formatting Integer with a decimal point

穿精又带淫゛_ 提交于 2019-12-12 04:58:15

问题


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



来源:https://stackoverflow.com/questions/42800554/formatting-integer-with-a-decimal-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!