用小数点格式化整数

时间:2017-03-15 03:24:00

标签: java formatting decimal-point

我有一个整数值,通过蓝牙从PLC设备读取,第一个数字代表一个小数位。例如:100必须格式化为10.0。另一个例子:

500 -> 50.0
491 -> 49.1
455 -> 45.5

以下行将使其成功:

data11.put("Text2", String.format("%.1f", (float)(mArray[18] & 0xFF | mArray[19] << 8) / 10.0));

但是......有没有其他方法可以使用 String.format 而不除以10.0来做同样的事情?

谢谢

4 个答案:

答案 0 :(得分:3)

以下方式怎么样?

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

答案 1 :(得分:2)

如果您关注的是浮动表示形式发生的内部舍入,请考虑使用BigDecimal。像:

***************************
APPLICATION FAILED TO START
***************************

Description:

The bean 'requestMappingHandlerMapping' could not be injected as a 'org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping' because it is a JDK dynamic proxy that implements:


Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

或合并为

BigDecimal v = BigDecimal.valueOf(500,1);
System.out.println(v.toString());

或者您可能需要使用

System.out.println(BigDecimal.valueOf(500,1).toString());

直接回答你的原始问题,即使这样也有效:

System.out.println(BigDecimal.valueOf(500,1).toPlainString());

但真正的问题是,这是否真的需要。

答案 2 :(得分:1)

这个怎么样?

System.out.println(500*0.1);
System.out.println(491*0.1);
System.out.println(455*0.1);

输出

50.0                                                                                                                                                                                                  
49.1                                                                                                                                                                                                  
45.5 

答案 3 :(得分:0)

我会通过整数除法和模数:

private static String format(int value) {
    return (value / 10) + "." + Math.abs(value % 10);
}
如果不使用负数,则可以删除

Math.abs()

private static String format(int value) {
    return (value / 10) + "." + (value % 10);
}

显然这个方法可以内联......

相关问题