有没有办法自动对java中的值进行舍入?
例如:
//generate a random integer value
int randomVal = RandomHelper.nextIntFromTo(1, otherVal);
/* then divide the integer value in half... the error I am getting is that its a double, probably
because the number generated isn't an even number, but I NEED it to be an integer. Can I round up?*/
int value = randomVal * 0.5;
答案 0 :(得分:3)
您可以添加1然后除以2而不是乘以0.5。这样,您可以避免浮点运算,然后转换为int。
int value = (randomVal + 1) / 2;
答案 1 :(得分:1)
使用Math.ceil()
:
int value = (int)Math.ceil(randomVal * 0.5);