【发布时间】:2011-11-18 18:57:09
【问题描述】:
我刚刚写了一个小方法来计算手机短信的页数。我没有选择使用Math.ceil 进行四舍五入,老实说,它看起来很丑。
这是我的代码:
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";
System.out.printf("COunt is %d ",(int)messagePageCount(message));
}
public static double messagePageCount(String message){
if(message.trim().isEmpty() || message.trim().length() == 0){
return 0;
} else{
if(message.length() <= 160){
return 1;
} else {
return Math.ceil((double)message.length()/153);
}
}
}
我不太喜欢这段代码,我正在寻找一种更优雅的方式来做这件事。有了这个,我期待 3 而不是 3.0000000。有什么想法吗?
【问题讨论】:
-
对于大多数业务代码,Math.ceil 更具人类可读性。
标签: java math types formatting