简体   繁体   English

四舍五入到最接近的整数 - 我是在作弊还是这已经足够了?

[英]Rounding Down to nearest whole number - am I cheating or is this more than adequate?

Essentially, if the number generated is 2.3 then if I subtract .5 it will then be 1.8 but the rounding function will make it 2, which is what I want.本质上,如果生成的数字是 2.3,那么如果我减去 0.5,它将是 1.8,但舍入函数将使它成为 2,这就是我想要的。 Or if the answer is 2.99999 and I subtract .5, the answer is 2.49999 which should round down to 2 which is what I want.或者,如果答案是 2.99999 并且我减去 0.5,那么答案是 2.49999,它应该四舍五入到 2,这就是我想要的。 My question is if the answer is 2 even and I subtract .5, the answer is now 1.5, so will it still round up to 2.我的问题是,如果答案是偶数 2 并且我减去 0.5,那么答案现在是 1.5,所以它仍然会四舍五入为 2。

temp1_1= Math.round(temp2_2/(360/temp_value)-.5);

this is my line of code for this.这是我的代码行。

There is already a function to do that.已经有一个功能可以做到这一点。 It's called floor :它被称为地板

double d = Math.floor(2.9999) //result: 2.0

Even simpler and potential faster更简单,潜力更快

double d = 2.99999999;
long l = (long) d; // truncate to a whole number.

This will round towards 0. Math.floor() rounds towards negative infinity.这将向 0 舍入。 Math.floor() 向负无穷大舍入。 Math.round(x - 0.5) also rounds towards negative infinity. Math.round(x - 0.5) 也向负无穷大舍入。

Everyone always wants to use fancy functions, but forgets about the humble modulus.每个人都想使用花哨的函数,却忘记了不起眼的模数。 My solution:我的解决方案:

number = x-(x%1);

subtracts the remainder of division by one, so x = 2.999 will = 2, 3.111 will = 3 and so on.将除法的余数减去 1,因此 x = 2.999 将 = 2,3.111 将 = 3,依此类推。 The cool thing about this is that you can round down the multiple of anything just by changing that 1 into whatever you like.关于这个很酷的事情是,您可以通过将 1 更改为您喜欢的任何值来舍入任何值的倍数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM